has_many:通过两次使用“master”表

时间:2017-03-10 16:38:02

标签: ruby-on-rails

我正在尝试使用“master”表创建一个has_many:through关系两次:

"Diagram of the relation"

我怎么做?

1 个答案:

答案 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