1

我实在想不通这个。我已经阅读了很多关于批量分配错误的类似问题,但我尝试过的每个解决方案都失败了。

我正在尝试使用 accept_nested_attributes_for 和 simple_form 将我的机构模型嵌套到我的课程模型中。我的代码如下:

课程模式:

  # 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"}
4

2 回答 2

2

您需要将institution_attributes 添加到课程的attr_accessible 并为fields_for 使用正确的名称,我认为它应该是:institution,而不是:institutions。表单应如下所示:

<%= 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 %>
于 2012-09-18T07:05:24.137 回答
0

您是否在控制器中“建立”了机构?

尝试包括:

@course.build_institution

在你的 CoursesController

于 2013-09-29T07:28:37.277 回答