答案 0 :(得分:0)
假设你有类似的东西:
Table: friendships
id : integer
friend_id : integer
friend_of_id : integer
class Friendship < ActiveRecord::Base
belongs_to :friend, class: :user, inverse_of:
belongs_to :friend_of, class: :user, inverse_of:
end
class User < ActiveRecord::Base
has_many :friendships, class: :friendship, foreign_key: :friend_of, inverse_of: friend_of
has_many :friends, through: :friendships
has_many :friendships_of, class: :friendship, foreign_key: :friend, inverse_of: :friend
has_many :friends_of, through: :friendships
end
我希望我能做到这一点,缺乏好的术语会让人感到困惑,如果你能想出更好的东西,那么它就会变得更容易。
根据此代码,您可以添加:
class User < ActiveRecord::Base
...
def add_friend(friend)
# left out checking if they are already a friend
friendships.create!( friend: friend)
friendships_of.create!( friend_of: friend)
end
end