Rails - 模型疑问
鉴于我有这样的模型:
class Person
has_many :owned_groups, :class_name => "Group", :foreign_key => :owner_id
has_many :owned_group_memberships, :through => :owned_groups,
:source => :group_memberships
has_many :group_memberships, :foreign_key => "member_id"
has_many :groups, :through => :group_memberships
end
class GroupMembership
belongs_to :member, :class_name => 'Person'
belongs_to :group
end
class Group
belongs_to :owner, :class_name => "Person"
has_many :group_memberships
has_many :members, :through => :group_memberships
end
How can I access the members
a group
has?我总是做 @group.members
或类似的事情,给我一个错误,说在模型中找不到关系。
提前致谢。
##EDIT##
我收到的错误是:无法在模型组中找到关联“group_memberships”
Given the fact that I have models like this:
class Person
has_many :owned_groups, :class_name => "Group", :foreign_key => :owner_id
has_many :owned_group_memberships, :through => :owned_groups,
:source => :group_memberships
has_many :group_memberships, :foreign_key => "member_id"
has_many :groups, :through => :group_memberships
end
class GroupMembership
belongs_to :member, :class_name => 'Person'
belongs_to :group
end
class Group
belongs_to :owner, :class_name => "Person"
has_many :group_memberships
has_many :members, :through => :group_memberships
end
How can I access the members
a group
has? Always I do @group.members
or things like that, gives me an error saying that the relation can't be found in the model.
Thanks in advance.
##EDIT##
The error I'm getting is: Could not find the association "group_memberships" in model Group
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在我正在开发的网站上做了类似的事情,但关联与你的做法有点不同,但也许会有帮助。我认为您需要使用 has_and_belongs_to_many 关联来加入多对多关联。
在我的数据库中,我有 Users、Members 和 UsersMembers
您不需要创建 UsersMembers 模型(在您的情况下为 GroupMembership),但您确实需要一个数据库表来链接这两者。
由此我现在可以调用 @band.members 或 @user.bands
I do a similar thing on a site I'm working on but the associations are a little different to how you're doing it but maybe it'll help. I think you need to use the has_and_belongs_to_many association to join up your many-to-many's.
In my database I have Users, Members and UsersMembers
You don't need to create a UsersMembers model (GroupMembership in your case) but you do need a database table to link the two.
From this I can now call @band.members or @user.bands
您可能需要指定 :class_name => has_many :members 语句中的“Person”。
You may need to specify :class_name => 'Person' in your has_many :members statement.