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 を実行すると

私はこのエラーレーキに直面しています! 保護された属性をまとめて割り当てることはできません: 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

上記の 2 つの回答のいずれかを使用するか、application.rb で保護を無効にして、次のようにホワイト リスト属性を false に設定できます。

config.active_record.whitelist_attributes = false

また、confirm_at を attr_accessible として追加できますが、Ahmad Sherif が述べたように、confirm_at を設定して新しいユーザーを作成する必要はありません。

于 2012-12-30T12:46:04.177 に答える