2012-08-10 39 views
3

遷移不能大規模指派保護屬性3.2.3

class CreateUsers < ActiveRecord::Migration 
    def change 
    create_table :users do |t| 
     t.string :name 
     t.string :password_digest 

     t.timestamps 
    end 
    end 
end 

型號

class User < ActiveRecord::Base 
    attr_accessible :name, :password_digest 
    validates :name, :presence => true, :uniqueness => true 
    has_secure_password 
end 

用戶註冊_form

.main_form 
    = form_for @user do |f| 

    %div 
     = f.label :name 
     = f.text_field :name, :size=>40 

    %div 
     = f.label :password, "Password" 
     = f.password_field :password 

    %div 
     = f.label :password_confirmation, "Confirmation" 
     = f.password_field :password_field 

    %div 
     = f.submit 'Create user' 

當我嘗試註冊一個新用戶它會拋出異常

ActiveModel::MassAssignmentSecurity::Error in UsersController#create 

Can't mass-assign protected attributes: password, password_field 

我做錯了什麼?

回答

5

您應該將這兩個字段添加到您的has_accessible列表中。 Rails不僅可以保護數據庫字段不受大量分配,而且還可以保護所有字段,如「虛擬」字段。

在用戶模型(而非attr_accesible線):

attr_accessible :name, :password_field, :password 

此外,password_digest不應該提供在任何情況下進行修改,這是一個計算的字段不用戶輸入。

+0

我應該添加哪些文件? – Alexandre 2012-08-10 10:13:43

+0

對不起,我忘了提及,它需要在'User'模型中。用你的'attr_accesible'行代替我的,它應該可以工作。 – Matzi 2012-08-10 10:15:20

相關問題