虽然使用在的has_many关系时访问额外的属性在连接表 [英] Access extra attributes in join table when using though in has_many relationship
问题描述
我正在考虑加入的has_many关系之间的一些额外的属性。
I was considering adding some extra properties between a has_many relationship.
例如,我有一个用户表,组表。用户可以通过加入群:通过的has_many关系。我想补充的该组中的用户的角色的属性。
For example, I have a Users table, and a Group table. Users can join groups via a :through has_many relationship. I want to add the property of the 'role' of the user in that group.
create_table "groupization", :force => true do |t|
t.integer "user_id"
t.integer "group_id"
t.string "role"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
我在想,我怎么能进入角色属性。我的想法是这样的:
I was wondering, how can I access the role attribute. I was thinking something like:
user.groups[0].role
那是一个正确的做法?我知道的语法错误(我试过);将正确的语法是什么样的?谢谢!
Is that a correct approach? I know the syntax is wrong (I tried it); what would the correct syntax be like? Thanks!
推荐答案
在您的用户模型中,你必须是这样的:
In your User model, you'll have something like:
class User < ActiveRecord::Base
has_many :groupizations
has_many :groups, :through => :groupizations
end
您只希望通过在控制台中的has_many
关系 groupizations
这样的访问角色信息。
You'd access the role information just through the has_many
relationship to groupizations
like this in the console.
foo = User.first
bar = foo.groupizations.first
bar.role
假设你对第一个用户groupizations。
Assuming you had groupizations on the first user.
使用一个特定的用户/组的关系,可以这样做:
Getting a specific user/group relationship could be done like this:
Groupizations.where("group_id = ? and user_id = ?", group.id, user.id)
然后从那里你可以得到你所寻找的角色。
Then from there you could get the role you were looking for.
这篇关于虽然使用在的has_many关系时访问额外的属性在连接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!