问题描述
我正在尝试创建以下内容:
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 中最好的方法是什么.
推荐答案
您很可能需要两个结构如下的模型:
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 在 此讨论 关于 Rails 论坛.)
<小时>请注意:这已经很老了.您可能需要考虑评估在现代 Rails 环境中处理此问题的其他策略.
问题描述
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.