Rails 4 nested attributes not saving

别来无恙 提交于 2019-11-28 08:34:06

Looks like you're using the wrong form builder object. Change the question section to something like this:

<%= f.fields_for :question do |question_builder| %>
   <%= question_builder.label :content %>
   <%= question_builder.text_area :content %>

   <%= question_builder.fields_for :answer do |answer_builder| %> 
       <%= answer_builder.label :content, "Answer" %>
       <%= answer_builder.text_field :content %>
   <% end %>

<% end %>

Originally you were using the f form builder in the line f.fields_for :answers..., however given your model code, since it is a Question that accepts_nested_attributes_for an Answer, we simply exchange the form builder object for the one used for the question section.

Note: I changed the names of the builder objects for clarity.

Update

In order to build a deeply nested relationship like this, you will have to loop through your "built" association (questions in this case), and invoke build again on its has_many association. So going off of gabrielhilal's answer, you would do this:

def new
  @survey = Survey.new
  @survey.questions.build
  @survey.questions.each do |question|
      question.answers.build
  end
end

Note that in your case, since you are explicitly creating only one question, you can technically do this instead (instead of the loop):

@survey.questions.first.answers.build

Disclaimer: If there is a cleaner, more Rails-y, way to do this, I am sadly unaware of it.

In your controller you have questions_id:

def survey_params
  params.require(:survey).permit(:name, 
    questions_attributes: [
      :content, :id, :survey_id, 
      answers_attributes: [:content, :id, :questions_id]
    ]
  )
end

Is that a typo? Also try setting action_on_unpermitted_parameters to :raise in you development.rb to see if there is any attribute that you' re missing in your survey_params method.

# In case of unpermitted parameters in the controller raise error.
config.action_controller.action_on_unpermitted_parameters = :raise

You must change your new action to include @survey.questions.build:

def new
  @survey = Survey.new
  @survey.questions.build
end

But your form is wrong as well. Change the question to questions

 <%= f.fields_for :questions do |builder| %> #questions
   <%= builder.label :content %>
   <%= builder.text_area :content %>

You must do the same thing for answers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!