0

我收到这个错误

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”,还有其他方法吗?

这是我的模型/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

这是我的模型/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

这是我的模型/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

这是我的控制器/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

感谢您的想法和指点。

4

1 回答 1

1

问题是这段代码:

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

这将返回完整的属性集,包括 created_at 和 updated_at 日期,然后您将其传递给 create,因此进行批量分配。

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

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
于 2012-07-29T06:44:55.687 回答