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


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

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中最好的方法是什么。


9796
2018-06-22 13:57


起源



答案:


您很可能想要两种结构如下:

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 %>

(这种模式来自一个帖子 瑞安贝茨 大约两年前 这个讨论 上 RailsForum。)


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


15
2018-06-22 14:04



太好了,谢谢! - cakeforcerberus


答案:


您很可能想要两种结构如下:

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 %>

(这种模式来自一个帖子 瑞安贝茨 大约两年前 这个讨论 上 RailsForum。)


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


15
2018-06-22 14:04



太好了,谢谢! - cakeforcerberus


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

所以基本上


类用户

  has_many:links,:through =>:relationship

结束

阶级关系

  belongs_to:user_id_1,:class =>“User”
  belongs_to:user_id_2,:class =>“User”

结束


1
2018-06-22 14:05