我有一个使用嵌套模型的注册表单。客户端可以有多个用户,一个User
属于一个Client
。在注册表单上,我希望能够同时注册客户和用户。但是,我不断收到用户的“无法批量分配”,因为我有accepts_nested_attributes_for :users
.
<h1>Sign Up</h1>
<%= form_for @client do |client_form| %>
<% if @client.errors.any? %>
<div class="error_messages">
<h2>Form is invalid</h2>
<ul>
<% for message in @client.errors.full_messages %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= client_form.label :business_name %>
<%= client_form.text_field :business_name %>
</div>
<%= client_form.fields_for :user do |user_form| %>
<div class="field">
<%= user_form.label :first_name %>
<%= user_form.text_field :first_name %>
</div>
</div>
<div class="field">
<%= user_form.label :last_name %>
<%= user_form.text_field :last_name %>
</div>
<div class="field">
<%= user_form.label :username %>
<%= user_form.text_field :username %>
</div>
<div class="field">
<%= user_form.label :password %>
<%= user_form.password_field :password %>
</div>
<div class="field">
<%= user_form.label :password_confirmation %>
<%= user_form.password_field :password_confirmation %>
</div>
<% end %>
<div class="actions"><%= client_form.submit %></div>
<% end %>
class Client < ActiveRecord::Base
attr_accessible :business_name
attr_accessible :users_attributes
has_many :users
has_many :items
accepts_nested_attributes_for :users, allow_destroy: true
...
end
class User < ActiveRecord::Base
attr_accessible :client_id, :first_name, :last_name, :username, :password, :password_confirmation
belongs_to :client
has_secure_password
....
end
错误
ActiveModel::MassAssignmentSecurity::Error - Can't mass-assign protected attributes: user:
(gem) activemodel-3.2.11/lib/active_model/mass_assignment_security/sanitizer.rb:48:in `process_removed_attributes'
(gem) activemodel-3.2.11/lib/active_model/mass_assignment_security/sanitizer.rb:20:in `debug_protected_attribute_removal'
(gem) activemodel-3.2.11/lib/active_model/mass_assignment_security/sanitizer.rb:12:in `sanitize'
(gem) activemodel-3.2.11/lib/active_model/mass_assignment_security.rb:230:in `sanitize_for_mass_assignment'
(gem) activerecord-3.2.11/lib/active_record/attribute_assignment.rb:75:in `assign_attributes'
(gem) activerecord-3.2.11/lib/active_record/base.rb:497:in `initialize'
app/controllers/clients_controller.rb:45:in `new'
app/controllers/clients_controller.rb:45:in `create'
(gem) actionpack-3.2.11/lib/action_controller/metal/implicit_render.rb:4:in `send_action'
(gem) actionpack-3.2.11/lib/abstract_controller/base.rb:167:in `process_action'
(gem) actionpack-3.2.11/lib/action_controller/metal/rendering.rb:10:in `process_action'
(gem) actionpack-3.2.11/lib/abstract_controller/callbacks.rb:18:in `block in process_action'
(gem) activesupport-3.2.11/lib/active_support/callbacks.rb:414:in `_run__330478543754893527__process_action__2034132490286778675
__callbacks'
这里有什么问题?