警告:当我使用gem''omniauth-identity时,“无法批量分配受保护的属性:created_at,updated_at”

时间:2012-07-29 03:52:06

标签: ruby-on-rails gem omniauth identity mass-assignment

我收到此错误

ActiveModel::MassAssignmentSecurity::Error in SessionsController#create

Can't mass-assign protected attributes: created_at, updated_at

我想我可以添加一些代码来解决这个问题。

class User < ActiveRecord::Base
  attr_accessible :email, :nickname, :authentications_attributes, :created_at, :updated_at

为什么Omniauth会更改created_at和updated_at? 除了添加“attr_accessible:created_at,:updated_at”之外,还有其他方法吗?

这是我的models / user.rb

class User < ActiveRecord::Base
  attr_accessible :email, :nickname, :authentications_attributes, :created_at, :updated_at
  validates :nickname, :presence => true
  validates :email, :presence => true, :uniqueness => true
  has_many :authentications

  accepts_nested_attributes_for :authentications

  class << self
    def from_auth(auth)
      Authentication.find_by_provider_and_uid(auth[:provider],
                                              auth[:uid]).try(:user) ||
        create!(
          :nickname => auth[:info][:nickname],
          :email => auth[:info][:email],
          :authentications_attributes => [
            Authentication.new(:provider => auth[:provider],
                               :uid => auth[:uid]
                              ).attributes
      ])
    end
  end


end

这是我的models / identity.rb

class Identity < OmniAuth::Identity::Models::ActiveRecord
  attr_accessible :nickname, :email, :password, :password_confirmation, :authentications_attributes
  validates_presence_of :nickname, :email
  validates_uniqueness_of :nickname, :email
  validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
end

这是我的models / authentication.rb

class Authentication < ActiveRecord::Base
  attr_accessible :user_id, :provider, :uid, :authentications_attributes, :created_at, :updated_at
  validates :provider, :presence => true, :uniqueness => {:scope => :user_id}
  validates :uid, :presence => true, :uniqueness => {:scope => :provider}
  belongs_to :user
end

这是我的controllers / sessions_controller.rb

class SessionsController < ApplicationController
  def create
    user = User.from_auth(request.env['omniauth.auth'])
    session[:user_id] = user.id
    flash[:notice] = "Welcome #{user.nickname}"
    redirect_to root_path
  end
end

感谢您的想法和指示。

1 个答案:

答案 0 :(得分:1)

问题在于这段代码:

Authentication.new(:provider => auth[:provider],
                   :uid => auth[:uid]
                  ).attributes

这将返回完整的属性集,包括created_at和updated_at日期,然后您将传递给它们进行创建,以便进行批量分配。

您可以创建用户,然后像这样构建属性:

authentication = Authentication.find_by_provider_and_uid(auth[:provider], 
                                                       auth[:uid]).try(:user)

unless authentication
  user = create!(
      :nickname => auth[:info][:nickname],
      :email => auth[:info][:email])
  user.authentications.build(:provider => auth[:provider])
end