2014-06-15 54 views
0

Rails 4.1.1,Devise 3.2.4其中一個參數在註冊時未分配給用戶

我生成了對現有用戶模型的設計視圖。之後,我添加了新的字段給用戶表格 - 角色。和編輯生成的註冊視圖:

<h2>Sign up</h2> 

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> 
    <%= devise_error_messages! %> 

    <div><%= f.label :email %><br /> 
    <%= f.email_field :email, autofocus: true %></div> 

    <div><%= f.label :password %><br /> 
    <%= f.password_field :password, autocomplete: "off" %></div> 

    <div><%= f.label :password_confirmation %><br /> 
    <%= f.password_field :password_confirmation, autocomplete: "off" %></div> 

    <div> 
    <%= f.label :role %><br /> 
    <%= f.collection_select :role, User::ROLES, :to_s, lambda{|r| r.to_s.humanize} %> 
    </div> 

    <div><%= f.submit "Sign up" %></div> 
<% end %> 
<%= render "devise/shared/links" %> 

但是,當新用戶註冊他的作用是nil。從POST請求表單數據:

utf8:✓ 
authenticity_token:LEieRtzF0iYnhop/EzcU328Dyg1jKNT8DV5eqgkPERA= 
user[email]:[email protected] 
user[password]:123123 
user[password_confirmation]:123123 
user[role]:author 
commit:Sign up 

用戶模式:

class User < ActiveRecord::Base 
    devise :database_authenticatable, :rememberable, :registerable 
    ROLES = %i[admin moderator author] 
    has_many :products 
end 

用戶模式:

create_table "users", force: true do |t| 
    t.string "email",    default: "", null: false 
    t.string "encrypted_password", default: "", null: false 
    t.string "username" 
    t.string "role" 
    t.datetime "remember_created_at" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

    add_index "users", ["email"], name: "index_users_on_email", unique: true 

那麼,什麼是問題?

>User.last 
    User Load (0.2ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1 
=> #<User id: 7, email: "[email protected]", encrypted_password: "$2a$10$44A0uITgRB7DWvKInk3n1.YZyUPs6ZyKtKvMtPSfoi/...", username: nil, role: nil, remember_created_at: nil, created_at: "2014-06-15 08:03:06", updated_at: "2014-06-15 08:03:06"> 
+0

如果您的用戶模型包含的方法 '角色',嘗試改變'用戶:用'USER ROLES':角色' – sidney

+0

@sidney,用戶模型沒有角色方法。提供的型號代碼 –

+0

好吧我現在看到感謝您的代碼。請單獨用'%'代替'%i',就像這樣:'ROLES =%[admin moderator author]' – sidney

回答

1

鐵路4器具strong parameters,這需要你有則params的白名單被分配到你的模型對象。這是爲了保護敏感屬性不被惡意用戶篡改URL或表單所覆蓋。 Devise指出,默認情況下它允許sign_upsign_inaccount_update動作的某些屬性,但是您有責任通過手動追加所需的任何附加參數。

class ApplicationController < ActionController::Base 
    before_action :configure_permitted_parameters, if: :devise_controller? 

    protected 

    def configure_permitted_parameters 
    devise_parameter_sanitizer.for(:sign_up) << :role 
    end 
end 

看看

  1. Rails 4, Strong Parameters, and Deprecation of the Attr_accessible Macro
  2. Devise wiki on strong params
相關問題