质量分配错误simple_form嵌套属性

时间:2012-09-18 07:02:18

标签: ruby-on-rails-3 nested-attributes simple-form mass-assignment

我真的无法想出这个。我已经阅读了很多关于质量分配错误的类似问题,但我尝试过的每个解决方案都失败了。

我正在尝试使用accepts_nested_attributes_for&和我的课程模型嵌入我的课程模型简单的形式。我的代码如下:

课程模型:

  # Attributes 
  attr_accessible :class_end, :class_start, :cost, :effort, :level, :name, :overview, :prerequisites, :tags, :tag_list

  # Associations 
  belongs_to :institution 
  accepts_nested_attributes_for :institution 

机构型号:

# Attributes
attr_accessible :bio, :city, :country, :name, :state, :twitter_url, :type, :url, :image_url, :email

 # Associations
 has_many :courses

嵌套的simple_form视图:

<%= simple_form_for(@course) do |f| %>
  <%= f.simple_fields_for :institutions do |i| %>
    <%= i.input :name %>            
    <%= f.input :name %>
    <%= f.input :overview %>
    <%= f.input :cost %> 
    <%= f.input :level %>
    <%= f.input :tag_list %> 
    <%= f.input :class_start %>
    <%= f.input :class_end %>
    <%= f.input :effort %>
    <%= f.input :prerequisites %>

    <%= f.button :submit %>
  <% end %>
<% end %>

我得到的错误:

Can't mass-assign protected attributes: institutions

{"utf8"=>"✓",
 "authenticity_token"=>"GRoBHYhpv3QyzvH2UHBaJQ/62+9QIDKIwp/VLiLMjus=",
 "course"=>{"institutions"=>{"name"=>"asdfa"},
 "name"=>"sdaf",
 "overview"=>"asdf",
 "cost"=>"Free",
 "level"=>"Beginner",
 "tag_list"=>"asdf",
 "class_start(1i)"=>"2012",
 "class_start(2i)"=>"9",
 "class_start(3i)"=>"18",
 "class_end(1i)"=>"2012",
 "class_end(2i)"=>"9",
 "class_end(3i)"=>"18",
 "effort"=>"asdf",
 "prerequisites"=>"asdf"},
 "commit"=>"Create Course"}

2 个答案:

答案 0 :(得分:2)

你需要将institution_attributes添加到课程的attr_accessible并使用fields_for的正确名称,我认为应该是:机构,而不是:机构。表格应如下所示:

<%= simple_form_for(@course) do |f| %>
  <%= f.simple_fields_for :institution do |i| %>
    <%= i.input :name %>            
  <% end %>
  <%= f.input :name %>
  <%= f.input :overview %>
  <%= f.input :cost %> 
  <%= f.input :level %>
  <%= f.input :tag_list %> 
  <%= f.input :class_start %>
  <%= f.input :class_end %>
  <%= f.input :effort %>
  <%= f.input :prerequisites %>

  <%= f.button :submit %>
<% end %>

答案 1 :(得分:0)

你在控制器中“建立”了这个机构吗?

尝试包括:

@course.build_institution

在您的CoursesController