2012-07-09 29 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, 
相關問題