我有一个质量分配错误。我不明白为什么它会给我错误 这里的错误
ActiveModel::MassAssignmentSecurity::Error in CustomersController#edit
Can't mass-assign protected attributes: gender
这是我的模特
Customer GenderManager Gender
ID Id Id
First isVisible Description
Last GroupID
Email
...
这是我的关系
class Customer < ActiveRecord::Base
# RELATIONSHIP
#Gender
has_many :gender_managers
accepts_nested_attributes_for :gender_managers, allow_destroy: :true
end
class GenderManager < ActiveRecord::Base
# RELATIONSHIP
belongs_to :customer
has_one :gender
attr_accessible :customer_id, :friendship_group_id, :isUsed,
:isVisible, :genders_attributes
accepts_nested_attributes_for :gender, allow_destroy: :true
end
class Gender < ActiveRecord::Base
belongs_to :gender_manager
attr_accessible :description, :gender_managers_id
end
CustomerController
def edit
@customer = Customer.find(params[:id])
@customer.gender_managers.build(:gender => Gender.new)
@bm = current_customer.book_managers.build
end
表格
<%= form_for @customer, :html => {:multipart => true} do |f| %>
<div class="customer_edit_error_message">
<%= render 'shared/error_messages' %>
</div>
<fieldset>
<div class="customer_edit_name">
<%= f.label :first_name %>
<%= f.text_field :first_name %>
</div>
<div class="customer_edit_middle_name">
<%= f.label :middle_name %>
<%= f.text_field :middle_name %>
</div>
<div class="customer_edit_last_name">
<%= f.label :last_name %>
<%= f.text_field :last_name %>
</div>
<%= f.fields_for :gender_managers do |gendermanagers| %>
<fieldset>
<%= gendermanagers.fields_for :genders do |genders| %>
<%= genders.label :description %>
<%= genders.select :description %>
<% end %>
<div><%= gendermanagers.label :friendship_group_id, "Show To: " %>
<%= gendermanagers.text_field :friendship_group_id %></div>
<div><%= gendermanagers.check_box :isVisible %>
<%= gendermanagers.label :isVisible %></div>
</fieldset>
<% end %>
<div class="customer_edit_button">
<%= f.submit "Save changes", class: "button_accept" %>
</div>
<% end %>
答案 0 :(得分:1)
您可能需要使用build_gender
方法来构建关联。
gender_manager = @customer.gender_managers.build
gender_manager.build_gender
此答案已经过编辑,以反映在接受的答案中给出的更正后的代码。
答案 1 :(得分:1)
您是否尝试过将:gender
添加到attr_accessible
模型中的GenderManager
列表中?
但我发现上面的答案更好,只有一个小的修正:
gender_manager = @customer.gender_managers.build
gender_manager.build_gender