簡體   English   中英

如何使用Rolify和Devise在注冊控制器及其視圖中為用戶分配角色

[英]How to assign role to user in Registration Controller and its view with Rolify and Devise

我想讓radiobuttongroup在我的視圖中選擇角色,但我不知道如何處理它。 我已經設置了寶石rolify和設計,但我不知道如何在視圖和控制器中分配角色。 我已經在控制台中創建了角色。 我想確保在選擇角色時沒有任何漏洞。 例如,如果該人試圖從瀏覽器更改角色名稱並將其分配給自己(例如管理員),那將是一個大問題。

registrations_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: [:create]

  def create
    super
  end

  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:firstname, :lastname, :email, :terms_of_service])
  end

user.rb

class User < ApplicationRecord
  rolify

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable, :lockable, :timeoutable
  validates :terms_of_service, :allow_nil => false, :acceptance => true

end

注冊視圖的一部分

<%= form_for(resource, as: resource_name, :role => "form", url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>
  <div class="form-group">
    <%= f.label t('label.user.form_content.firstname') %><br/>
    <%= f.text_field :firstname, autofocus: true, :class => "form-control text-center" %>
  </div>
  <div class="form-group">
    <%= f.label t('label.user.form_content.lastname') %><br/>
    <%= f.text_field :lastname, :class => "form-control text-center" %>
  </div>
  <div class="form-group">
    <%= f.label t('label.user.form_content.email') %><br/>
    <%= f.email_field :email, :class => "form-control text-center" %>
  </div>
  <div class="row">
    <div class="col-md-6">
      <div class="form-group">
        <%= f.label t('label.user.form_content.password') %>
        <% if @minimum_password_length %>
            <em>(<%= @minimum_password_length %> characters minimum)</em>
        <% end %><br/>
        <%= f.password_field :password, autocomplete: "off", :class => "form-control text-center" %>
      </div>
    </div>
    <div class="col-md-6">
      <div class="form-group">
        <%= f.label t('label.user.form_content.password_confirmation') %>
        <% if @minimum_password_length %>
            <em>(Must be same with password)</em><br/>
        <% end %><br/>
        <%= f.password_field :password_confirmation, autocomplete: "off", :class => "form-control text-center" %>
      </div>
    </div>
  </div>
<% end %>

我在嘗試使用rolify管理復雜功能時遇到了類似的問題,我在User模型中為角色驗證提供了一個非常好的解決方案,我會留下一個鏈接,以防你想要查看它。

Rolify:在User模型中驗證具有復雜功能的角色

另外,我在registrations_controller中添加用戶注冊后的角色,我將留下另一個鏈接,顯示如何執行此操作:

通過Form使用Rolify以及Devise和Cancan動態添加角色

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM