警告:无法批量分配受保护的属性

时间:2011-03-01 05:03:56

标签: ruby-on-rails ruby ruby-on-rails-3

在对/:username / about发帖时,我收到了“警告:无法批量分配受保护的属性:约”。

class About < ActiveRecord::Base
  belongs_to :user
  accepts_nested_attributes_for :user
  attr_accessible :user_id, :sexuality, :relationship_status, :living_with, :religion, :web, :languages 
  attr_accessible :appearance_ethnicity, :appearance_height, :appearance_weight, :appearance_hair, :appearance_piercings, :appearance_tattoo, :appearance_eyes_color
  attr_accessible :interest_list, :music_list, :movie_list, :book_list, :tv_list
  validates_presence_of :user_id
end

class User < ActiveRecord::Base
  ...
  accepts_nested_attributes_for :about
end

class AboutsController < ApplicationController
  def update 
    @user = User.first(:conditions => ["lower(username) = ?", params[:username].downcase]) if true
    @about = @user.about
    if @about.update_attributes(params[:about])
      flash[:notice] = "Successfully updated post."
      respond_with(@about, :location => about_path(@about.user.username))
    else
      redirect_to :edit
    end
  end 
end

我正在接受

 Started POST "/heaven/about" for 127.0.0.1 at Tue Mar 01 02:57:08 -0200 2011
 Processing by AboutsController#update as HTML
 Parameters: {"commit"=>"Update Profile", "authenticity_token"=>"7/Xcv0z07A3JvsTiDlapoghi25sIjgiFfhN33hFWfoU=", "utf8"=>"✓", "username"=>"roses", "about"=>{"about"=>{"sexuality"=>"not_specified", "book_list"=>"", "relationship_status"=>"not_specified", "appearance_eyes_color"=>"not_specified", "music_list"=>"", "appearance_height"=>"", "living_with"=>"not_specified", "movie_list"=>"", "tv_list"=>"", "appearance_hair"=>"not_specified", "religion"=>"not_specified", "web"=>"", "interest_list"=>"", "appearance_weight"=>"", "appearance_piercings"=>"", "appearance_tattoo"=>""}}}
 WHERE type = 'table' AND NOT name = 'sqlite_sequence'
  User Load (0.8ms)  SELECT "users".* FROM "users" WHERE (lower(username) = 'heaven') LIMIT 1
  About Load (0.5ms)  SELECT "abouts".* FROM "abouts" WHERE ("abouts".user_id = 2) LIMIT 1
WARNING: Can't mass-assign protected attributes: about
CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE ("users"."id" = 2) LIMIT 1
Redirected to http://localhost:3000/heaven/about
Completed 302 Found in 832ms

感谢。

4 个答案:

答案 0 :(得分:35)

您需要设置attr_accessible :about_attributes

答案 1 :(得分:5)

确保您在About模型中的attr_accessible中提到的about模型中尝试更新的所有字段。

答案 2 :(得分:3)

问题在于参数中的额外about"about"=>{"about"=>{"sexuality"...

您的表单中可能包含以下内容:

<%= form_for @about do |f| %>
  <%= f.fields_for @about do |a| %>
     <%= a.text_field :sexuality %>
     ...
  <% end %>
<% end %>

fields_for阻止导致参数中的额外about。只需删除它,你应该好好去。

答案 3 :(得分:1)

这发生在我身上,因为我在生成器创建模型后通过迁移添加了一列。因此,如果添加列,请编辑模型。