Rails 3: Devise add roles checkboxes to registration form

我与影子孤独终老i 提交于 2019-12-21 21:54:40

问题


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 %>

回答1:


check your console, I was getting a 'Can't mass assign" error, then I put :role_ids into the user model's attr_accessible and it worked.



来源:https://stackoverflow.com/questions/4622635/rails-3-devise-add-roles-checkboxes-to-registration-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!