使用Devise gem创建用户时更新数据库字段

时间:2015-07-10 01:42:02

标签: ruby-on-rails devise

说明

我想在注册帐户时设置用户的安全级别。我不希望这是注册表单中的隐藏字段,因为一个人可以发送他们自己的值来尝试获得管理权限。所以,它需要在RegistrationController中。

版本

Ruby:2.2.1p85(2015-02-26修订版49769)[x86_64-darwin14]

Rails:4.2.0

文件

这是我到目前为止所拥有的。

app/config/routes.rb文件中添加了以下行:

devise_for :users, :skip => [:sessions, :registrations], 
           :controllers => { registrations: 'users/registrations' }

devise_scope :user do
    get    "login",             to: "devise/sessions#new",          as: :new_user_session
    post   "login",             to: "devise/sessions#create",       as: :user_session
    delete "logout",            to: "devise/sessions#destroy",      as: :destroy_user_session

    get    "register",           to: "devise/registrations#new",     as: :new_user_registration
    post   "register",           to: "devise/registrations#create",  as: :user_registration
    get    "account/delete",     to: "devise/registrations#cancel",  as: :cancel_user_registration

    get    "user/profile/edit",  to: "devise/registrations#edit",    as: :edit_user_registration

    patch  "user",              to: "devise/registrations#update"
    put    "user",              to: "devise/registrations#update"
    put    "register",          to: "devise/registrations#update"
    delete "user/delete",       to: "devise/registrations#destrony"

    get    "user/profile",      to: 'devise/registrations#edit',    as: :user_root
end

这是app/controllers/users/registration_controller.rb文件中的RegistrationController:

class Devise::RegistrationsController < DeviseController

    before_filter :configure_permitted_parameters, :only => [:create]

    def create
        super
          resource.update_attribute(:security_level, '1')
    end
end

我的数据库确实为所有用户提供了一个名为“security_level”的字段。

提前感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:0)

您将来可能面临逻辑重复问题(例如,从控制台创建用户不会强制Rails填充安全级别属性,因此您需要在每个位置控制此操作)。最好在User模型中使用回调:

class User < ActiveRecord::Base

  before_save :set_security_level

  def set_security_level
    self.security_level = 1
  end
end

因此,每次用户将被保存时,:set_security_level将被执行。

回调手册http://guides.rubyonrails.org/active_record_callbacks.html

答案 1 :(得分:0)

如果您想设置security_level = 1,默认情况下,我建议您将其写入rails迁移。

迁移代码

change_column_default :users, :security_level, '1'

如果您想通过覆盖默认设计克里特函数来做更多事情,请使用以下代码。

class RegistrationsController < Devise::RegistrationsController
  def create
    super do
        resource.security_level = '1'
        resource.save
    end
  end
end