Let's start with a little context. Suppose we want to add the populer 'friends' feature for our users, we already have User model, what we need is a join table 'friendships' to connect users.
class User < ActiveRecord::Base
end
class CreateFriendships < ActiveRecord::Migration
def self.up
create_table :friendships, :id => false do |t|
t.integer :left_user_id
t.integer :right_user_id
end
end
def self.down
drop_table :friendships
end
end
The behavior we want, can be written like this:
test "should has many friends" do
users(:quentin).friends << users(:aaron)
assert_equal 1, users(:quentin).friends.reload.count
end
Of course the test is failed when we run it now. After reading our requirements we decide to use has_and_belongs_to_many (habtm) in ActiveRecord because it is enough for now, so we modify our User model like this:
class User < ActiveRecord::Base
has_and_belongs_to_many :friends, :join_table => 'friendships',
:foreign_key => 'left_user_id', :association_foreign_key => 'right_user_id',
:class_name => 'User'
end
Now run our test, passed, perfect! We can leave office and enjoy *fill whatever you like* now.
"Wait", your brilliant colleague says, and add one line to your unit test:
test "should has many friends" do
users(:quentin).friends << users(:aaron)
assert_equal 1, users(:quentin).friends.reload.count
assert_equal 1, users(:aaron).friends.reload.count
end
He runs the test again and it failed. It's unfair if quentin treat aaron as his friend but aaron doesn't do the same to quentin, isn't it? To fix this problem we need to custom insert and delete sql for the habtm relationship:
class User < ActiveRecord::Base
has_and_belongs_to_many :friends, :join_table => 'friendships',
:foreign_key => 'left_user_id', :association_foreign_key => 'right_user_id',
:class_name => 'User',
:insert_sql => 'insert into friendships (`left_user_id`, `right_user_id`) values
(#{id}, #{record.id}), (#{record.id}, #{id})',
:delete_sql => 'delete from friendships where (left_user_id = #{id} and right_user_id
= #{record.id}) or (left_user_id = #{record.id} and right_user_id = #{id})'
end
What we do here, is to add two friendship records (both direction) when we add a user to another's friends set. We do the same when delete a user from one's friends set. We rerun the test and it passes as we expected.
Note the ":id => false" argument when we create the join table 'friendships', without it you'll have troubles when loading friends objects. I think this is a long history bug of ActiveRecord, I don't know why it is not fixed. If you really want to keep the 'id' field and use habtm at the same time, a workaround is customize the finder_sql:
class User < ActiveRecord::Base
has_and_belongs_to_many :friends, ...
:finder_sql => 'select users.* from friendships left outer join users on
friendships.right_user_id = users.id where friendships.left_user_id = #{id}'
end
The bidirectional habtm we build here, is in fact a self-referential bidirectional relationship, it relates models to the same type of models (users to users). What will happen if the relationship is NOT self referential?
In that case we should not use habtm, otherwise our (at least my) brain will be burned by the complicated sqls it brings. Don't waste time on those sqls, ActiveRecord provides another way to build many-to-many relationship: has_many :through
So one day the boss comes to you and asks, "Can we group our friends? I want to put Gates in group Evil and Male, and Linus in group Minix and Antarctic"
"Sure", you answered, how can you say No to your boss?
Now the many-to-many relationship is between groups and users, we need to modify User model, create a Group model and write a migration to modify friendships table. Since we'll use has_many :through for this requirement, we also need a model for the join table 'friendships':
class User < ActiveRecord::Base
has_many :groups
end
class CreateGroups < ActiveRecord::Migration
def self.up
create_table :groups do |t|
t.string :name
t.integer :user_id
end
end
def self.down
drop_table :groups
end
end
class Group < ActiveRecord::Base
belongs_to :user
has_many :friendships
has_many :friends, :through => :friendships
end
class RemodelFriendships < ActiveRecord::Migration
def self.up
remove_column :friendships, :left_user_id
rename_column :friendships, :right_user_id, :friend_id
change_column :friendships, :group_id, :integer, :null => false
end
def self.down
change_column :friendships, :group_id, :integer, :null => true
rename_column :friendships, :friend_id, :right_user_id
add_column :friendships, :left_user_id
# execute "..."
end
end
class Friendship < ActiveRecord::Base
belongs_to :group
belongs_to :friend, :class_name => 'User'
validates_uniqueness_of :friend_id, :scope => :group_id
end
Pretty good, it works. But we have the same problem when we use habtm, the relationship is not bidirectional. How can we fix it?
ActiveRecord allow you to extend the association proxy when use has_many :through, the solution here is to override the proxy's default CRUD methods. Let's create a new file lib/bidirection.rb:
module Bidirection
def <<(friend)
Friendship.create :group_id => friend.groups.default.id, :friend_id => self.proxy_owner.user.id
super(friend)
end
[:delete, :destroy].each {|m|
define_method(m) {|friends|
friends = [friends] unless friends.instance_of?(Array)
friends.each {|friend|
Friendship.first(:conditions => {:group_id => friend.groups.default.id, :friend_id => self.proxy_owner.user.id}).try m
}
super(friends)
}
}
end
Then enhance our has_many :through with it:
class Group < ActiveRecord::Base
...
has_many :friends, :through => :friendships, :extend => Bidirection
end
That's it, you have bidirectional many-to-many relationship between groups and users now. For convinient you can create a default group when create user (use before_create hook), and delegate friends and friends= methods in User model to user's default group, in that way you get the self-referential bidirectional many-to-many relationship betweent users back, as we have when using habtm.
Was a very helpful read. Thanks.
ReplyDeletejust realizing the habtm self-referential is a big mess in AR, thanks, the post is very helpful.
ReplyDelete-Amir
Found this very helpful, thanks!
ReplyDelete