为用户和位置创建分配管理员

时间:2013-01-04 00:22:37

标签: ruby-on-rails devise nested-forms cancan rolify

我有一个用于用户注册的嵌套模型表单,它可以同时创建用户和位置。我希望自动为创建位置的用户分配admin角色。我正在使用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" %>

1 个答案:

答案 0 :(得分:0)

您需要在控制器中添加user.add_role :admin, location来处理请求后的注册表单。这可能是users_controller.rb函数

中的create