我正在使用在Mac OS X Lion上运行的Rails 1.9.3。我试图将记录添加到我的数据库,我得到以下错误:
hisham-agil:twitster hisham$ rails console
Loading development environment (Rails 3.2.5)
1.9.3p194 :001 > User.new(name: 'hilarl', email: 'hilaal@gmail.com', password_digest: 'food', password_confirmation: 'food')
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: password_digest
from /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activemodel-3.2.5/lib/active_model/mass_assignment_security/sanitizer.rb:48:in `process_removed_attributes'
from /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activemodel-3.2.5/lib/active_model/mass_assignment_security/sanitizer.rb:20:in `debug_protected_attribute_removal'
from /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activemodel-3.2.5/lib/active_model/mass_assignment_security/sanitizer.rb:12:in `sanitize'
from /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activemodel-3.2.5/lib/active_model/mass_assignment_security.rb:230:in `sanitize_for_mass_assignment'
from /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.5/lib/active_record/attribute_assignment.rb:75:in `assign_attributes'
from /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.5/lib/active_record/base.rb:498:in `initialize'
from (irb):1:in `new'
from (irb):1
from /usr/local/rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.5/lib/rails/commands/console.rb:47:in `start'
from /usr/local/rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.5/lib/rails/commands/console.rb:8:in `start'
from /usr/local/rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.5/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
我的用户模型:
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation
end
enter code here
我的数据库架构:
ActiveRecord::Schema.define(:version => 20120601171139) do
create_table "users", :force => true do |t|
t.string "name"
t.string "email"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "password_digest"
end
end
我使用默认的sqlite3作为数据库。
答案 0 :(得分:3)
批量分配通常意味着将属性传递给调用,该调用将对象创建为属性哈希的一部分。
试试这个:
@user = User.new(name: 'hilarl', email: 'hilaal@gmail.com')
@user.password_digest = 'food'
@user.save
另见:
http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html
答案 1 :(得分:0)
password_digest
在您的用户模型中不是attr_accessible。
将第一行更改为:
attr_accessible :email, :name, :password, :password_confirmation, :password_digest