更新嵌套属性:警告:无法批量分配受保护的属性:错误

时间:2012-02-17 01:05:36

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

我花了很多时间在这上面,拉了一半头发。帮助

user

    has_may :rights
    attr_accessible :rights_attributes

right

    belongs_to :user
    attr_accessible :user_id, :pgd_id, :link_id

查看:

<%= semantic_form_for @user, :url => {:action => "rightsupdate", :id => @user.id} do |f| %>$
  <%= f.inputs do %>$
    <%= f.input :pgds, :as => :check_boxes, :required => false %>$
  <% end %>$
    <%= f.input :link_id, :value => @owner.link_id, :as => :hidden %>$
    <%= f.buttons %>$
<% end %>$

但是当我更新时,它一直在说:

WARNING: Can't mass-assign protected attributes: pgd_ids, link_id

我可以通过向用户pdg添加:pgd_ids而不是attr_accessible来绕过link_idlink_id插入为NULL

1 个答案:

答案 0 :(得分:0)

首先,您需要确保模型包含accepts_nested_attributes

user.rb

attr_accessible :rights_attributes
has_may :rights
accepts_nested_attributes :rights

然后,您需要将权限字段包装到fields_for块中。看起来你使用的是Formtastic,我并不熟悉,但我觉得它应该是这样的:

<%= semantic_form_for @user, :url => {:action => "rightsupdate", :id => @user.id} do |f| %> 
  <%= f.semantic_fields_for :rights do |builder| %>
    <%= builder.inputs do %>
      <%= builder.input :pgds, :as => :check_boxes, :required => false %>
    <% end %>
    <%= builder.input :link_id, :value => @owner.link_id, :as => :hidden %>
    <%= builder.buttons %>
  <% end %>
<% end %>

Railscasts在嵌套表单上有一些免费的截屏视频,值得查看上面的代码并不能解决问题。