2013-01-04 78 views
0

我有一個用戶註冊的嵌套模型表單,它同時創建一個用戶和一個位置。我希望創建位置的用戶自動分配管理員角色。我正在使用devise/cancan/rolify。任何想法如何做到這一點?指定管理員在用戶和位置創建

能力模型

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    user ||= User.new # guest user (not logged in) 
    if user.has_role? (:admin, Location.first) 
     can :manage, :all 
    end 

選址模型

class Location < ActiveRecord::Base 
    resourcify 
    has_and_belongs_to_many :users 
    accepts_nested_attributes_for :users, :allow_destroy => true 
    attr_accessible :lat, :long, :name, :street_address, :places_id, :user_attributes 
    validates_uniqueness_of :places_id, :message => "location already taken" 
end 

用戶模型

class User < ActiveRecord::Base 
    has_and_belongs_to_many :locations 
    accepts_nested_attributes_for :location 
    rolify 
    resourcify 
    # Include default devise modules. Others available are: 
    # :token_authenticatable, :confirmable, 
    # :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :role_ids, :as => :admin 
    attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :location_attributes 
end 

榜樣

class Role < ActiveRecord::Base 
    has_and_belongs_to_many :users, :join_table => :users_roles 
    belongs_to :resource, :polymorphic => true 

    scopify 
end 

最後,形式註冊

<% resource.build_location %> 
<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => {:class => 'form-vertical' }) do |f| %> 
<%= f.error_notification %> 
<%= f.fields_for :location do |location_form| %> 
<%= location_form.text_field :name, "data-geo" => "name" %> 
<%= location_form.text_field :places_id, "data-geo" => "id" %> 
<% end %> 

    <%= f.input :name, :autofocus => true %> 
    <%= f.input :email, :required => true %> 
    <%= f.input :password, :required => true %> 
    <%= f.input :password_confirmation, :required => true %> 
    <%= f.button :submit, 'Sign up', :class => 'btn-primary' %> 
<% end %> 
<%= render "devise/shared/links" %> 

回答

0

您需要在您的控制器將處理註冊表單POST請求添加user.add_role :admin, location。這可能是你users_controller.rb中的create功能

相關問題