轨道-如何创建一个与另一个模型的TWO相连的模型[英] Rails - How to create a model linked to TWO of another model

本文是小编为大家收集整理的关于轨道-如何创建一个与另一个模型的TWO相连的模型的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

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

User model (this is fine)

id

Link model (associated with two Users)

id
user_id1
user_id2

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

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

我只是不确定在铁轨中做到这一点的最佳方法是什么.

推荐答案

您很可能需要两个模型,如下所示:

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 大约两年前此讨论 Railsforum .)


只是注意:现在已经很旧了.您可能需要考虑评估在现代铁路背景下处理此问题的其他策略.

其他推荐答案

您可以创建一个联接模型,该模型在两个用户模型之间的链接之间的关系

基本上是


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

本文地址:https://www.itbaoku.cn/post/627410.html

问题描述

I am trying to create the following:

User model (this is fine)

id

Link model (associated with two Users)

id
user_id1
user_id2

Is this an instance in which I would want to use the has_and_belongs_to_many association type on the Link model? How should I do this?

Ultimately, I would like to be able to have a user object and call @user.links to get all links involving that user...

I'm just not sure what the best way to do this in Rails is.

推荐答案

You will very likely want two models structured as follows:

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

(This pattern is from a post made by Ryan Bates about two years ago during this discussion on RailsForum.)


Just a note: this is now quite old. You may want to consider evaluating other strategies for handling this in a modern Rails context.

其他推荐答案

You can create A Join Model that relation between the Link between the two users models

so basically


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