简体   繁体   中英

Rails 3: Devise add roles checkboxes to registration form

I'm using Devise for user registration. I've been reading the all famous tutorial about customizing Devise, but can't understand this simple task. I followed his model (HABTM)

I want to add a roles check box to the Devise edit form. I don't have a Controller cause Devise doesn't provide one, but managed to add a default role to new users. I was able to display the checkboxes with the correct info checked but can't edit it (it won't save anydata). Do I need a custom controller? if yes, how exactly? I'm new to HABTM relations!

My User model

    class User < ActiveRecord::Base
  has_and_belongs_to_many :roles

  before_save :setup_role

  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me

  def role?(role_sym)
    roles.any? { |r| r.name.underscore.to_sym == role_sym }
  end

  # Default role is "User"
  def setup_role 
    if self.role_ids.empty?     
      self.role_ids = [3] 
    end
  end


end

My edit form (devise/registrations/edit.html.rb

    <h2>Edit <%= resource_name.to_s.humanize %></h2>

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %>
  <%= devise_error_messages! %>

  <p><%= f.label :email %><br />
  <%= f.text_field :email %></p>

  <p><%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
  <%= f.password_field :password %></p>

  <p><%= f.label :password_confirmation %><br />
  <%= f.password_field :password_confirmation %></p>

  <p><%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
  <%= f.password_field :current_password %></p>

    <% for role in Role.find(:all) %> 
        <div> 
          <%= check_box_tag "user[role_ids][]", role.id, @user.roles.include?(role) %> 
          <%= role.name %> 
        </div> 
    <% end %>

  <p><%= f.submit "Update" %></p>
<% end %>

<h3>Cancel my account</h3>

<p>Unhappy? <%= link_to "Cancel my account", registration_path(resource_name), :confirm => "Are you sure?", :method => :delete %>.</p>

<%= link_to "Back", :back %>

检查您的控制台,出现“无法批量分配”错误,然后将:role_ids放入用户模型的attr_accessible中,并且它起作用了。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM