无法批量分配受保护的属性:confirmed_at

时间:2012-12-30 11:34:41

标签: ruby-on-rails devise

我正在使用rails中的设计验证创建一个演示应用

我正面临这个错误

rake aborted!
Can't mass-assign protected attributes: confirmed_at

我的User.rb类是

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :name, :email, :password, :password_confirmation, :remember_me
  # attr_accessible :title, :body

validates_presence_of :name
validates_uniqueness_of :name, :email, :case_sensitive => false
end

和我的db.seed.rb文件代码是

# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
#   cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
#   Mayor.create(name: 'Emanuel', city: cities.first)

puts 'SETTING UP DEFAULT USER LOGIN'
user = User.create! :name => 'First User', :email => 'user@example.com', :password => 'please', :password_confirmation => 'please', :confirmed_at => DateTime.now
user2 = User.create! :name => 'Second User', :email => 'user2@example.com', :password => 'please', :password_confirmation => 'please', :confirmed_at => DateTime.now
puts 'New user created: ' << user.name

user.rb是一个模型类。 当我运行命令 $ bundle exec rake db:seed

我正面临这个错误   耙子流产了!     无法批量分配受保护的属性:confirmed_at

3 个答案:

答案 0 :(得分:4)

您可以使用:

Model.create!(fieldsValues, :without_protection => true) 

在你的情况下:

User.create!({:name => 'First User', :email => 'user@example.com', :password => 'please', :password_confirmation => 'please', :confirmed_at => DateTime.now}, :without_protection => true)

without_protection将允许您设置受保护字段的值

答案 1 :(得分:3)

创建用户时,您不必真正设置confirmed_at,而是可以在每个用户对象上调用confirm!并完成,这样做会更好'因为调用{{1}除了设置confirm!之外,还会做很多其他事情。

confirmed_at

答案 2 :(得分:1)

您可以使用以上两个答案中的任何一个或在application.rb中禁用保护,将白名单属性设置为false,如:

config.active_record.whitelist_attributes = false

并且,您可以将confirmed_at添加为attr_accessible,但您不需要像Ahmad Sherif所提到的那样设置confirm_at来创建新用户。