2

我正在使用 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

我正面临这个错误 rake aborted!无法批量分配受保护的属性:confirmed_at

4

3 回答 3

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将允许您设置受保护字段的值

于 2012-12-30T12:23:03.733 回答
3

在创建用户时您实际上不必设置confirmed_at,相反,您可以调用confirm!每个用户对象就完成了,这更好,因为调用confirm!除了设置之外还有很多其他的事情confirmed_at

user = User.create! :name => 'First User', :email => 'user@example.com', :password => 'please', :password_confirmation => 'please'
user.confirm!
于 2012-12-30T11:40:07.310 回答
1

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

config.active_record.whitelist_attributes = false

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

于 2012-12-30T12:46:04.177 回答