0

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

1 回答 1

0

您将需要添加user.add_role :admin, location将处理注册表单发布请求的控制器。这可能是你users_controller.rbcreate功能

于 2013-01-04T08:03:42.400 回答