我已经检查了类似问题的几个答案,似乎所有人都认为问题是attr_accessible,但我似乎无法让这个工作。
基本上我有用户&地址模型,并希望将Address属性指定为嵌套属性。但是当我保存它会导致下面显示的无法质量分配属性错误。
我在下面的代码中尝试过attr_accessible的许多变体,例如:addresses_attributes,:address_attributes,:primary_address_attributes ...我不确定它为什么不起作用,也许是因为它在Member模块声明中?
有人可以帮忙吗?
class Member::User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# each user may have zero or many addresses
# their primary email is also set as their login id.
has_many :addresses
has_one :address, :class_name => "Member::Address", :conditions => "is_primary = true"
accepts_nested_attributes_for :addresses, :address
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :address_attributes
validates_presence_of :email
end
我提交嵌套字段(相关部分)的表单
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => {:class => "form-horizontal"}) do |f| %>
<small>Mandatory fields marked *</small><br><br>
<% devise_error_messages! %>
<% flash.each do |name, msg| %>
<div class="alert alert-<%= name == :notice ? "success" : "error" %>">
<a class="close" data-dismiss="alert">×</a>
<%= msg %>
</div>
<% end %>
<%= f.fields_for resource.build_primary_address do |address_form| %>
<div class="control-group">
<%= address_form.label :first_name, :class => "control-label" %>
<div class="controls">
<%= address_form.text_field :first_name, :class => "input-xlarge" %>
</div>
</div>
<div class="control-group">
<%= address_form.label :last_name, :class => "control-label" %>
<div class="controls">
<%= address_form.text_field :last_name, :class => "input-xlarge" %>
</div>
</div>
<% end %>
错误显示:
Can't mass-assign protected attributes: member_address
{"utf8"=>"✓",
"authenticity_token"=>"HrZJG2krn15veUKJVh6PgEs4wwufaeRhciHcUIn6AaM=",
"user"=>{"member_address"=>{"first_name"=>"asdf",
"last_name"=>"asdfsafd"},
"email"=>"Bob.JOnes@jones.com",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]"}}
答案 0 :(得分:1)
为了让rails了解表单中提交的主要地址是嵌套属性,您必须明确告诉它这里的关系:
<%= f.fields_for :address, resource.build_primary_address do |address_form| %>
。原因是,因为您的模型名称的作用域为Member::
,并且rails从类名称派生表单参数名称,所以在params哈希中最终使用:member_address而不是:address。因为:在这种情况下,地址是一个字段,其中:用户接受嵌套属性,:地址应表示为:params散列中的address_attributes,因此请确保后者出现在attr_accessible中。
答案 1 :(得分:0)
添加
attr_accessible :member_address
到用户模型。
说明:要初始化ActiveRecord实例的每个哈希键必须声明为attr_accessible。查看您的哈希键有:
"user"=>{"member_address"=>{ ... }}
初始化User实例的哈希中的member_address键,因此它必须包含在attr_accessible语句中。