0

即使我在模型中添加了accepts_nested_attributes_for。
它仍然说“无法批量分配受保护的属性”
为了避免这种情况我还应该做什么???

模型/用户.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 %>
4

2 回答 2

1

attr_accessible定义您希望用户能够批量分配的属性。只要确保它具有您想要的所有属性。

公平地说,attr_accessible如果您不关心它,您可以删除它并且错误将消失(但您的所有模型字段都可以批量分配)。

于 2012-07-09T02:35:27.303 回答
1

在edit.html.erb

错误的:

f.fields_for :nickname_attributes,

正确的:

f.fields_for :user_profile_attributes,
于 2012-08-30T19:40:42.597 回答