Rails 3:设计添加角色复选框到注册表单

时间:2011-01-07 04:56:37

标签: ruby-on-rails devise has-and-belongs-to-many

我正在使用Devise进行用户注册。我一直在阅读关于自定义Devise的所有famous tutorial,但无法理解这个简单的任务。我跟着他的模特(HABTM)

我想在Devise编辑表单中添加一个角色复选框。我没有控制器原因Devise没有提供,但设法为新用户添加默认角色。我能够显示选中正确信息的复选框,但无法编辑它(它不会保存任何数据)。我需要自定义控制器吗?如果有,怎么样?我是HABTM关系的新手!

我的用户模型

    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

我的编辑表单(设计/注册/ 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 个答案:

答案 0 :(得分:1)

检查你的控制台,我得到一个'无法批量分配'错误,然后我把:role_ids放入用户模型的attr_accessible并且它有效。