Note that there are some explanatory texts on larger screens.

plurals
  1. PORails & Rolify: Add default role on creation?
    primarykey
    data
    text
    <p>Currently I'm using <strong>Rolify &amp; CanCan</strong> to manage roles and abilities in my Rails 3 app. My question is: How can I get a user to have a role by default on creation? for example, if I have a "user" role, ¿How can I make all the users that register in my app have a <strong>user</strong> Role by default? My <strong>Ability.rb</strong> has this code:</p> <pre><code>class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user (not logged in) if user.has_role? :admin can :manage, :all elsif user.has_role? :user can :update, User, :id =&gt; user.id end end end </code></pre> <p>My <strong>User Model</strong> has this one:</p> <pre><code>class User &lt; ActiveRecord::Base rolify authenticates_with_sorcery! attr_accessible :username, :email, :password, :password_confirmation validates_confirmation_of :password validates_presence_of :password, :on =&gt; :create validates_presence_of :username validates_uniqueness_of :username validates_presence_of :email validates_uniqueness_of :email end </code></pre> <p>The <strong>Role Model</strong> This One:</p> <pre><code>class Role &lt; ActiveRecord::Base has_and_belongs_to_many :users, :join_table =&gt; :users_roles belongs_to :resource, :polymorphic =&gt; true end </code></pre> <p>And From the <strong>UsersController</strong> we have:</p> <pre><code>def new @user = User.new end def create @user = User.new(params[:user]) if @user.save redirect_to users_path, :notice =&gt; "Tu usuario se ha guardado" else render "new" end end </code></pre> <p>Finally the <strong>Rolify Migration</strong> is this one:</p> <pre><code>class RolifyCreateRoles &lt; ActiveRecord::Migration def change create_table(:roles) do |t| t.string :name t.references :resource, :polymorphic =&gt; true t.timestamps end create_table(:users_roles, :id =&gt; false) do |t| t.references :user t.references :role end add_index(:roles, :name) add_index(:roles, [ :name, :resource_type, :resource_id ]) add_index(:users_roles, [ :user_id, :role_id ]) end end </code></pre> <p>Now, I can assign roles manually from the <strong>rails console</strong> by using:</p> <pre><code>1 User.all 2 User.find(id) 3 User.add_role(:role) </code></pre> <p>But how can I assign automatically a default role when <em>every user</em> it's created?</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload