简体   繁体   English

创建对象时的Ruby on Rails NoMethodError

[英]Ruby on Rails NoMethodError when creating object

I am trying to create a new object with group.group_member.build however this throws an error: 我正在尝试使用group.group_member.build创建一个新对象,但这会引发错误:

NoMethodError: undefined method `group_member' for #<Group:0x007fe50d5468f8>

group.rb group.rb

belongs_to :owner
has_many :group_members

group_member.rb group_member.rb

belongs_to :group

I used owner.build_group which successfully created the group, I'm under the impression that group.group_member.build should do the same for the group_member object. 我使用owner.build_group成功创建了组,给人的印象是group.group_member.build应该对group_member对象执行相同的group_member

I have also tried group.group_members.build which returns a slightly different error: 我也尝试过group.group_members.build返回一个略有不同的错误:

ActiveRecord::UnknownAttributeError: unknown attribute: group_id

All help is appreciated, I can't seem to figure out the issue here. 感谢所有帮助,我似乎无法在这里找出问题。 Thanks. 谢谢。

You need to use the name of the association, which is plural group.group_members . 您需要使用关联的名称,即复数group.group_members Update your code to use: 更新您的代码以使用:

group.group_members.build

Your group_members table will need to have a group_id column for this to work. 您的group_members表将需要有一个group_id列才能起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM