【问题标题】:Active Model MassAssignmentSecurity Error活动模型 MassAssignmentSecurity 错误
【发布时间】:2012-10-22 09:47:18
【问题描述】:

我遇到了一个错误:我正在使用 Facebook 集成开发一个网站。我是 ruby​​ on rails 的新手。你能帮我解决我的问题吗?

ActiveModel::MassAssignmentSecurity::Error in SessionsController#create

Can't mass-assign protected attributes: name

这是我的控制器:

class SessionsController < ApplicationController
  def create
    #render :json => request.env['omniauth.auth'].to_yaml
   auth = request.env['omniauth.auth']
    unless @auth = Authorization.find_from_hash(auth)
      @auth = Authorization.create_from_hash(auth, current_user)
    end

    self.current_user = @auth.user  
    render :text => "Welcome, #{current_user.name}."
   end
end

这是我的用户模型:

class User < ActiveRecord::Base
  has_many :authorizations
  attr_accessor :name, :uid, :provider

  def self.create_from_hash!(hash)
    #create(:name => hash['user_info']['name'])
   create(:name => hash.info.name)
  end
end

这是我的授权模型:

class Authorization < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :user_id, :uid, :provider
  validates_uniqueness_of :uid, :scope => :provider

  def self.find_from_hash(hash)
    find_by_provider_and_uid(hash['provider'], hash['uid'])
  end

  def self.create_from_hash(hash, user = nil)
    user ||= User.create_from_hash!(hash)
    Authorization.create(:user => user, :uid => hash['uid'], :provider => hash['provider'])
  end
end

我该如何解决这个问题 .. 在此先感谢 :)

【问题讨论】:

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


    【解决方案1】:

    您当然启用了mass assignment protection(在您的配置文件中使用config.active_record.whitelist_attributes = true),因此您需要明确指出哪些属性可以通过update_attributes 等方法进行更新。你可以使用attr_accessible

    User 模型中,替换以下行(看起来没用)

    attr_accessor :name, :uid, :provider
    

    attr_accessible :name, :uid, :provider
    

    请参阅与attr_accessorattr_accessible 相关的问题以获取更多信息hereherehere

    【讨论】:

    • 实际上我昨晚成功了,但感谢您的回复 :).. 这正是我解决问题的方法 :D
    • 伙计,我运行了 sidekiq,它正在使用 update_attributes,因此引发了各种错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 2013-06-01
    • 2018-07-24
    • 2022-12-14
    相关资源
    最近更新 更多