创建记录时出错:nil 对象而不是数组?
我有一个包含许多帖子的主题,并接受它们的嵌套属性。当我创建主题时,它也会创建第一篇文章。
当调用 Topics#create
时,我在尝试评估 nil.[]=
时收到 NoMethodError
,并且我只是不知道是什么造成它。
创建方法:
@forum = Forum.find params[:forum_id]
params[:topic][:post_attributes][:member_id] = current_member.id
@topic = @forum.topics.create params[:topic]
respond_with @topic, location: topic_url(@topic)
我的新主题形式:
- @topic.posts.build
= form_for @topic do |topic_form|
= topic_form.label :title
= topic_form.text_field :title
= topic_form.fields_for :posts do |post_fields|
= post_fields.label :content
= post_fields.text_area :content
知道哪里出了问题吗?
I have a Topic
that has many Posts
, and accepts nested attributes for them. When I create a topic it creates a first post as well.
When Topics#create
is called I get a NoMethodError
when trying to evaluate nil.[]=
, and I just can't figure out what's causing it.
The create method:
@forum = Forum.find params[:forum_id]
params[:topic][:post_attributes][:member_id] = current_member.id
@topic = @forum.topics.create params[:topic]
respond_with @topic, location: topic_url(@topic)
My new topic form:
- @topic.posts.build
= form_for @topic do |topic_form|
= topic_form.label :title
= topic_form.text_field :title
= topic_form.fields_for :posts do |post_fields|
= post_fields.label :content
= post_fields.text_area :content
Any idea on what is wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的猜测是,它在这一行:
您可能应该将其更新为:
或
因为您使用的是 has_many 关联,所以可能会随该主题提交多个帖子,因此 post_attributes 的参数实际上是一个大批。
My guess is that it is on this line:
You should probably update it to:
or
Because you are using a has_many association there is a potential for more than one post to be submitted with the topic, therefore the params for the post_attributes are actually an array.
它与邮政有很多关联吗?
也许你应该尝试:
Is it a has many association for Post ?
Maybe you should try with :