问题
Im trying to figure out how to do a mutual 2-way relationship, that is:
user_id friend_id
1 2
2 1
In above user 1 and user 2 would be friends if both user_id = 1 has friend_id = 2 and friend_id = 2 has user_id = 2 as there friend in a table. How to count all the 2-way mutual relations in ActiveRecord?
回答1:
What you're looking for is a has_and_belongs_to_many relationship:
class User < ActiveRecord::Base
has_and_belongs_to_many :friends, :class_name => "User",
:foreign_key => "this_user_id",
:association_foreign_key => "other_user_id"
end
Example is from §4.4.2.1.
回答2:
Read the final chapter of Micheal Heartl Ruby on Rails Tutorial: Learn Rails by Example where he explains these kind of examples really well. There is a free online edition here.
https://www.railstutorial.org/book/following_users
Take a look at the final chapter. I hope it helps.
来源:https://stackoverflow.com/questions/9671829/ruby-on-rails-getting-a-2-way-friend-relationship-in-active-record