关联无效。 确保accepts_nested_attributes_for用于:问题关联

我正在rails 4中构建嵌套表单。我不断收到此错误

我的_form.html.erb为

  

prohibited this project from being saved:


builder %>

_question.html.erb

  


3 %>


project.rb

  has_many :questions, :dependent => :destroy accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true 

编辑

question.rb

  class Question < ActiveRecord::Base belongs_to :project end 

项目控制员

  def new @project = Project.new 3.times do question = @project.questions.build end def project_params params.require(:project).permit(:name) 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 

结束

我用“ nested_form ”gem给出了错误Invalid association. Make sure that accepts_nested_attributes_for is used for :questions association. Invalid association. Make sure that accepts_nested_attributes_for is used for :questions association.

请帮我摆脱这个错误

问题控制器def: –

  def question_params params.require(:question).permit(:project_id, :subject, :content) end 

您的问题可能与您的强参数有关

尝试将projects_controller中的project_params更改为

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

而且,您的控制器代码应如下所示

 def new @project = Project.new 3.times do @question = @project.questions.build 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 private def project_params params.require(:project).permit(:name,questions_attributes: [:project_id,:subject,:content]) end 

此外,您还必须使用accepts_nested_attributes_for查找强参数

更新

尝试将_form.html.erb更改为

 <%= nested_form_for(@project) do |f| %> <% if @project.errors.any? %> 

<%= pluralize(@project.errors.count, "error") %> prohibited this project from being saved:

    <% @project.errors.full_messages.each do |message| %>
  • <%= message %>
  • <% end %>
<% end %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.fields_for :questions do |builder| %> <%= render "question_fields", :ff => builder %> #changed to ff to avoid confusion <% end %>

<%= f.link_to_add "Add a questions",:questions %>

#this line it should be here.
<%= f.submit %>
<% end %>

你的_question_fields.html.erb

 

<%= ff.label :content, "Question" %>
<%= ff.text_area :content, :rows => 3 %>
<%= ff.label :subject, "Question" %>
<%= ff.text_field :subject %>
<%= ff.link_to_remove "Remove this task" %>