2011-01-07 92 views
2

我正在使用Devise进行用户注册。我一直在阅读关于定制设计的全部famous tutorial,但无法理解这个简单的任务。我跟着他的模型(HABTM)Rails 3:设计添加角色复选框到注册表格

我想添加角色复选框到设计编辑窗体。我没有控制器原因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

检查您的控制台,我得到一个“无法分配质量”错误,然后我把:role_ids放到用户模型的attr_accessible中,并且工作。