Allow users to select role from registration form with devise and rolify

856 views Asked by At

I want to allow users to select their role from checkboxes on the new user form.

Here are my relevant files.

MODELS:

## models\user.rb
class User < ActiveRecord::Base
   rolify
    devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
end

## models\role.rb
class Role < ActiveRecord::Base
   has_and_belongs_to_many :users, :join_table => :users_roles
   belongs_to :resource, :polymorphic => true
   scopify
end

CONTROLLER:

##controllers\users\registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
   # before_filter :configure_sign_up_params, only: [:create]
   # before_filter :configure_account_update_params, only: [:update]

   # GET /resource/sign_up
   def new
      super
   end

   ...
end

VIEW:

<div class="field">
  <%= f.label :roles %>
  <div class="controls">
    <% Role.all.each do |role| %>
        <%= check_box_tag "users_roles[role_ids][]", role.id, @user.role_ids.include?(role.id) %>
        <%= role.name %><br />
    <% end %>
  </div>
</div>

I can add roles from the console using

 user.add_role? :admin 

and it works fine. The role_ids column is in a table called user_roles. How do I write to this table from the new user form?

0

There are 0 answers