2012-07-29 43 views
0

我得到这个错误警告:“不能大规模指派保护属性:created_at,的updated_at”,当我使用的宝石'omniauth认同”

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 

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

问题是这段代码:

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 
+0

非常感谢您! – JeskTop 2012-07-30 13:48:03

+0

完全没问题:) – 2012-07-31 00:55:20

相关问题