【问题标题】:update attributes cause mass assignment exception, even with attr_accessible更新属性会导致批量分配异常,即使使用 attr_accessible
【发布时间】:2012-07-29 08:26:22
【问题描述】:

即使我在 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"}

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

【问题讨论】:

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


    【解决方案1】:

    在你的控制器中你应该使用

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

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

    【讨论】:

      【解决方案2】:

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

      即:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多