2

我有一个Topic,它有很多Posts,并接受它们的嵌套属性。当我创建一个主题时,它也会创建第一个帖子。

Topics#create被调用时,我NoMethodError在尝试评估时得到一个nil.[]=,我只是无法弄清楚是什么原因造成的。

创建方法:

@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

知道什么是错的吗?

4

2 回答 2

2

我的猜测是它在这条线上:

参数[:topic][:post_attributes][:member_id] = current_member.id

您可能应该将其更新为:

参数[:topic][:post_attributes][0][:member_id] = current_member.id

或者

params[:topic][:post_attributes].first[:member_id] = current_member.id

因为您使用的是 has_many 关联,所以可能会提交多个帖子与主题一起提交,因此 post_attributes 的参数实际上是一个数组。

于 2011-01-31T18:21:14.583 回答
1

Post 有很多关联吗?
也许你应该尝试:

params[:topic][:posts_attributes][0][:member_id] = current_member.id
于 2011-01-31T03:30:48.747 回答