2

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?

3
  • What line is the error pointing to ? Commented Jan 31, 2011 at 2:40
  • @Zabba: There is one line of code I had removed for testing before I copied it. Updated the question to include it. Error is happening on the second line. Commented Jan 31, 2011 at 3:08
  • And what are your incoming params? (They should be displayed in the error page, a bit lower down) Commented Jan 31, 2011 at 3:27

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way to simulate a has_one association in order to ensure only one post is ever submitted?
There are a couple ways. 1. Create a first_post attribute or has_one association of your own that you can use for this form - instead of the has_many posts association. 2. Hard-code the HTML to only allow for a single set of post-attributes - requires more manual work on your end. My suggestion would be to do what your doing now and then verify that only one post is submitted by checking the length of [:post_attributes] and making sure it's equal to 1 and not greater than 1.
1

Is it a has many association for Post ?
Maybe you should try with :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.