更新属性会导致质量分配异常,即使使用attr_accessible也是如此

时间:2012-07-29 08:26:22

标签: ruby-on-rails forms mass-assignment

即使我在attr_accessible

中有要更新的字段,也会收到以下错误
Can't mass-assign protected attributes: utf8, _method, authenticity_token, profile, commit, action, controller, id

我猜我不想保存的其他属性会引发异常,但我怎样才能过滤掉它们?

这是params hash

{"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"1aabj2DxleZoDu/U0SzGXSZrPcesRKXkIXTRVbk9f0A=",
 "profile"=>{"name"=>"Aaron Dufall",
 "company"=>"Supreme Windows",
 "location"=>"",
 "professional_bio"=>""},
 "commit"=>"Update",
 "id"=>"1"}

profiles_controller.rb

class ProfilesController < ApplicationController
    respond_to :html

    def edit
      @profile = Profile.find(params[:id])
      respond_with @profile
    end

    def update
        @profile = Profile.find(params[:id])
        if @profile.update_attributes(params)
           flash[:success] = "Profile sucessfully updated"
           redirect_to root_path
        else
           flash[:error] = "Profile failed to update"
           render 'edit'
        end
    end
end

profile.rb

class Profile < ActiveRecord::Base
  belongs_to :user
  attr_accessible :name, :company, :location, :professional_bio
end

2 个答案:

答案 0 :(得分:2)

在您的控制器中,您应该使用

if @profile.update_attributes(params[:profile])

这将仅过滤params上“profile”键下的属性。

答案 1 :(得分:0)

您可能需要考虑使用:without_protection - 它会跳过质量分配安全性。

即:

User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)

re:http://apidock.com/rails/ActiveRecord/Base/new/class