开发者

Error on record creation: nil object instead of array?

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开发者_Python百科
  = topic_form.fields_for :posts do |post_fields|
    = post_fields.label :content
    = post_fields.text_area :content

Any idea on what is wrong?


My guess is that it is on this line:

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

You should probably update it to:

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

or

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

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 :

params[:topic][:posts_attributes][0][:member_id] = current_member.id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜