当一个人应该使用A"的has_many:通过"关系在Rails的? [英] When should one use a "has_many :through" relation in Rails?

查看:163
本文介绍了当一个人应该使用A"的has_many:通过"关系在Rails的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想明白的has_many:通过,何时使用它(以及如何)。但是,我没有得到它。我读起的Rails 3,我试图谷歌搜索,但我不能够理解。

I am trying to understand what has_many :through is and when to use it (and how). However, I am not getting it. I am reading Beginning Rails 3 and I tried Googling, but I am not able to understand.

有人可以试着解释一下吗?

Can somebody try to explain?

推荐答案

假设你有两种模式:用户集团

Say you have two models: User and Group.

如果你想有用户属于组,那么你可以做这样的事情:

If you wanted to have users belong to groups, then you could do something like this:

class Group < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  has_many :groups
end

如果你想跟踪各地协会的其他元数据是什么?例如,当用户加入该组,或者用户的角色是该组中的什么?

What if you wanted to track additional metadata around the association? For example, when the user joined the group, or perhaps what the user's role is in the group?

这是你做联想第一类对象:

This is where you make the association a first class object:

class GroupMembership < ActiveRecord::Base
  belongs_to :user
  belongs_to :group

  # has attributes for date_joined and role
end

这引入了一个新表,并消除了用户的表中的 GROUP_ID 列。

This introduces a new table, and eliminates the group_id column from the user's table.

本code的问题是,你必须更新每一个地方其他你使用的用户类,并改变它:

The problem with this code is that you'd have to update every where else you use the user class and change it:

user.groups.first.name

# becomes

user.group_memberships.first.group.name

这类型的code很烂,这让像引入改变了这种痛苦。

This type of code sucks, and it makes introducing changes like this painful.

的has_many:通过 为您提供了两全其美的:

has_many :through gives you the best of both worlds:

class User < ActiveRecord::Base
  has_many :groups, :through => :group_memberships  # Edit :needs to be plural same as the has_many relationship   
  has_many :group_memberships
end

现在,你可以把它像一个正常的的has_many ,但得到的关联模型的好处,当你需要它。

Now you can treat it like a normal has_many, but get the benefit of the association model when you need it.

请注意,您也可以做到这一点与 HAS_ONE

Note that you can also do this with has_one.

编辑:因此很容易将用户添加到组

def add_group(group, role = "member")
  self.group_associations.build(:group => group, :role => role)
end

这篇关于当一个人应该使用A&QUOT;的has_many:通过&QUOT;关系在Rails的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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