何时使用“has_many :through"Rails 中的关系? [英] When to use a "has_many :through" relation in Rails?

查看:25
本文介绍了何时使用“has_many :through"Rails 中的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解 has_many :through 是什么以及何时使用它(以及如何使用).但是,我不明白.我正在阅读 Beginning 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.

推荐答案

假设你有两个模型:UserGroup.

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
  belongs_to :group
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.

这段代码的问题是你必须更新你使用用户类的所有其他地方并更改它:

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

这种类型的代码很糟糕,而且它使得引入这样的更改很痛苦.

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

has_many :through 为您提供两全其美:

has_many :through gives you the best of both worlds:

class User < ActiveRecord::Base
  has_many :group_memberships
  has_many :groups, :through => :group_memberships  # Edit :needs to be plural same as the has_many relationship   
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

这篇关于何时使用“has_many :through"Rails 中的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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