未初始化常量错误:无法获取此 has_many :通过正确
我一直在关注这个问题。在这里看到了类似的问题,但似乎我有一个额外复杂的因素;对他们有效的方法对我不起作用。
我有用户、组、组成员的模型和表格。组由用户拥有,但每个组可以有任意数量的组成员,即其他用户。以下是我的关联:
在用户中、
has_many :groups
在组中、
belongs_to :user
has_many :group_members
has_many :members, :class_name => "User", :through=>:group_members
在 GroupMember 中,
belongs_to :member, :class_name=>"User"
belongs_to :group
要获取组的成员,然后在 groups_controller.rb 中执行以下操作:
@groupmembers = @group.group_members.all
但是,这会生成以下错误:
NameError in GroupsController#show
uninitialized constant Group::GroupMember
就像我说的,我一直在周围并且围绕这个...我哪里出错了?预先感谢您的寻找...
I have been around and around with this. Have seen similar questions here but it seems I have an extra complicating factor; what worked for them doesn't work for me.
I have models and tables for User, Group, GroupMember. A group is owned by a user, but each group can have an arbitrary number of group members, i.e., other users. Here are my associations:
In User,
has_many :groups
In Group,
belongs_to :user
has_many :group_members
has_many :members, :class_name => "User", :through=>:group_members
In GroupMember,
belongs_to :member, :class_name=>"User"
belongs_to :group
To get at the members of a group, then, in groups_controller.rb I do this:
@groupmembers = @group.group_members.all
However, that generates the following error:
NameError in GroupsController#show
uninitialized constant Group::GroupMember
Like I say, I have been around and around with this... where have I gone wrong? Thanks in advance for looking...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我终于自己完成了这个工作。我缺少的部分是在 User 类中;因为 User 是 Member 的基础类,所以我需要这个:
belongs_to :groupmember, :foreign_key=>"member_id"
一旦就位,Rails 就能够找到它应该找到的所有内容,例如,
Group.find(1).members
现在查找属于 ID 为 1 的组的所有用户。I finally got this working on my own. The part I was missing was in the User class; since User is the underlying class of Member, I needed this:
belongs_to :groupmember, :foreign_key=>"member_id"
Once that was in place, Rails was able to find everything as it should, e.g,
Group.find(1).members
now finds all users who belong to the group with an ID of 1.假设您有一个名为 GroupMembers 的模型(您应该指定这是一个 has_many 直通关联),那么您的非直通关联在 Group 和 Member 模型上都应如下所示:
has_many :group_members, :class_name => “GroupMembers”
由于某种原因,rails 没有将关联中的第二个模型复数化,因此您自己执行即可。
Assuming you have a model called GroupMembers (which you should given this is a has_many through association), your non-through association should look like this on both the Group and Member models:
has_many :group_members, :class_name => "GroupMembers"
For some reason rails isn't pluralizing the second model in the association, so just do it yourself.
有时它也可以很简单,因为
belongs_to :model
需要是单数而不是复数。今天我在人际关系上犯了这个错误。Sometimes it can also be as simple as the
belongs_to :model
needs to be singular instead of plural. I made this mistake on my relationship today.