注册时,其中一个参数未分配给用户

时间:2014-06-15 08:24:01

标签: ruby-on-rails devise

Rails 4.1.1,Devise 3.2.4

我为现有的User模型生成了设计视图。之后我将新字段添加到用户表 - 角色。并编辑了生成的注册视图:

<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]:user4@test.com
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: "user4@test.com", 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">

1 个答案:

答案 0 :(得分:1)

Rail 4实现strong parameters,要求您将params的白名单分配给模型对象。这是为了保护敏感属性不被恶意用户篡改URL或表单所覆盖。设计说明默认情况下它允许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