Rails - 如何创建链接到另一个模型的TWO的模型

cak*_*rus 11 ruby ruby-on-rails

我正在尝试创建以下内容:

User model (this is fine)

id

Link model (associated with two Users)

id
user_id1
user_id2
Run Code Online (Sandbox Code Playgroud)

这是一个我想在链接模型上使用has_and_belongs_to_many关联类型的实例吗?我该怎么做?

最后,我希望能够拥有一个用户对象并调用@ user.links来获取涉及该用户的所有链接...

我只是不确定在Rails中最好的方法是什么.

Jos*_*man 15

您很可能想要两个结构如下的模型:

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, :through => :friendships #...
end

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => 'User', :foreign_key => 'friend_id'
end 

# ...and hence something like this in your view
<% for friendship in @user.friendships %>
  <%= friendship.status %>
  <%= friendship.friend.firstname %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

(这种模式来自Ryan Bates大约两年前在RailsForum 讨论期间发表的帖子.)


请注意:现在已经很老了.您可能需要考虑在现代Rails上下文中评估处理此问题的其他策略.