1

即使我在 attr_accessible 中有要更新的字段,我也会收到以下错误

Can't mass-assign protected attributes: utf8, _method, authenticity_token, profile, commit, action, controller, id

我猜我不想保存的其他属性正在引发异常,但是我该如何过滤掉它们呢?

这是参数哈希

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

profile_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

配置文件.rb

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

2 回答 2

2

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

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

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

于 2012-07-29T08:46:30.783 回答
0

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

IE:

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

回复:http ://apidock.com/rails/ActiveRecord/Base/new/class

于 2013-09-05T17:53:24.607 回答