Invalid association. Make sure that accepts_nested_attributes_for is used for :questions association

让人想犯罪 __ 提交于 2019-12-06 21:47:32

Might be your problem is with your strong parameters

Try changing your project_params in your projects_controller as

def project_params
  params.require(:project).permit(:name,questions_attributes: [:project_id,:subject,:content])
end

And also,your controller code should look like this

def new
  @project = Project.new
  3.times do
    @question = @project.questions.build
  end
end

def create
  @project = Project.new(project_params)

  respond_to do |format|
    if @project.save
      format.html { redirect_to @project, notice: 'Project was successfully created.' }
      format.json { render :show, status: :created, location: @project }
    else
      format.html { render :new }
      format.json { render json: @project.errors, status: :unprocessable_entity }
    end
  end
end

private

def project_params
  params.require(:project).permit(:name,questions_attributes: [:project_id,:subject,:content])       
end

Also,you have to look for Strong Parameters with accepts_nested_attributes_for.

Update

Try changing your _form.html.erb as

<%= nested_form_for(@project) do |f| %>
  <% if @project.errors.any? %>
    <div id="error_explanation">
    <h2><%= pluralize(@project.errors.count, "error") %> prohibited this project from being saved:</h2>

    <ul>
    <% @project.errors.full_messages.each do |message| %>
      <li><%= message %></li>
    <% end %>
    </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>

  <%= f.fields_for :questions do |builder| %>
    <%= render "question_fields", :ff => builder %> #changed to ff to avoid confusion
    <% end %>
    <p><%= f.link_to_add "Add a questions",:questions %></p> #this line it should be here.
    <div class="actions">
    <%= f.submit %>
    </div>
  <% end %>

And your _question_fields.html.erb as

<p>
  <%= ff.label :content, "Question" %><br />
  <%= ff.text_area :content, :rows => 3 %><br />
  <%= ff.label :subject, "Question" %><br />
  <%= ff.text_field :subject %><br />
  <%= ff.link_to_remove "Remove this task" %>       
</p>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!