2012-07-09 78 views
0

即使我向我的模型中添加了accep_nested_attributes_for。
它仍然说“不能批量分配受保护的属性”
我该怎么做才能避免这种情况?如何避免“无法批量分配受保护的属性”错误

型号/ user.rb

class User < ActiveRecord::Base 

    validates_presence_of :username 
    validates_uniqueness_of :username 
    validates_length_of :username, :within => 4..10 

    acts_as_messageable 

    has_one :user_profile 
    accepts_nested_attributes_for :user_profile 

    # Include default devise modules. Others available are: 
    # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, :confirmable, 
     :recoverable, :rememberable, :trackable, :validatable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :user_profile_attributes 

    def mailboxer_email(message) 
    email 
    end 

# def name 
# email 
# end 

end 

型号/ user_profile.rb

class UserProfile < ActiveRecord::Base 
belongs_to :user 
accepts_nested_attributes_for :user 
attr_accessible :nickname 
end 

的意见/注册/ edit.html.erb

<h2>Edit <%= resource_name.to_s.humanize %></h2> 

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %> 
    <%= devise_error_messages! %> 

    <div class="field"> 
    <%= f.label :nickname %><br /> 
    <%= f.fields_for :nickname_attributes, @user.user_profile do |user_profile| %> 
    <%= user_profile.text_field :nickname %> 
    <% end %> 
    </div> 

    <div><%= f.label :email %><br /> 
    <%= f.email_field :email %></div> 

    <div><%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br /> 
    <%= f.password_field :password %></div> 

    <div><%= f.label :password_confirmation %><br /> 
    <%= f.password_field :password_confirmation %></div> 

    <div><%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br /> 
    <%= f.password_field :current_password %></div> 

<%= recaptcha_tags :display => {:theme => 'red'} %> 

    <div><%= f.submit "Update" %></div> 
<% end %> 

<h3>Cancel my account</h3> 

<p>Unhappy? <%= link_to "Cancel my account", registration_path(resource_name), :confirm => "Are you sure?", :method => :delete %>.</p> 

<%= link_to "Back", :back %> 

回答

1

attr_accessible定义你想要的属性用户能够进行批量分配。只要确保它具有您想要的所有属性即可。

为了公平起见,如果您不关心它,并且错误将会消失(但您的所有模型字段将可以进行批量赋值),您可以删除attr_accessible

+0

谢谢,但它并没有我的情况下帮助:(似乎所有的,因为我'使用宝石'设计'根据这个链接它看起来像我需要添加@ user.build_user_profile。但是什么问题是该设计不会创建user_controller,因此没有文件t o编辑。 – MKK 2012-07-09 05:32:46

1
在edit.html.erb

错误:

f.fields_for :nickname_attributes, 

正确:

f.fields_for :user_profile_attributes, 
相关问题