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

时间:2009-06-22 13:57:15

标签: ruby-on-rails ruby

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

User model (this is fine)

id

Link model (associated with two Users)

id
user_id1
user_id2

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

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

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

2 个答案:

答案 0 :(得分: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 %>

(此模式来自Ryan Bates大约两年前在this discussion RailsForum期间发表的帖子。)


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

答案 1 :(得分:1)

您可以创建两个用户模型之间的链接关系

的连接模型

所以基本上


class User

  has_many :links, :through => :relationships

end

class Relationship

  belongs_to :user_id_1, :class=> "User"
  belongs_to :user_id_2, :class=> "User"

end