Rails - 如何创建一个链接到另一个模型的TWO的模型 [英] Rails - How to create a model linked to TWO of another model

查看:118
本文介绍了Rails - 如何创建一个链接到另一个模型的TWO的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create the following:

User model (this is fine)

id

Link model (associated with two Users)

id
user_id1
user_id2

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

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?

最终,我想要有一个用户对象,并调用@ user.links来获取涉及该用户的所有链接...

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

我只是不知道在Rails中做什么最好的方法是。

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

(此模式来自 Ryan Bates 大约两年前在这个讨论 RailsForum 。)

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

只是一个注释:现在已经很老了。您可能需要考虑评估在现代Rails环境中处理此问题的其他策略。

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

这篇关于Rails - 如何创建一个链接到另一个模型的TWO的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆