简体   繁体   中英

how to automatically add a role to a user when signing up using devise

I am using Devise 1.1.5. I got a roles and a roles_assignment table. Is it possible to assign a role automatically in my role_assignments table when the user signs up? Many thanks!

I tried this but it wont work

class User < ActiveRecord::Base  
  after_create :assign_role_after_sign_up

  protected  
    def assign_role_after_sign_up(user)  
      RoleAssignment.create(:role_id => 1, :user_id => user.id)  
    end
end

Your after_create method won't work because you're trying to pass user , which isn't much of anything in the model. All user attributes are actually accessible as instance variable, so you should instead do:

def assign_role_after_sign_up
  RoleAssignment.create(:role_id => 1, :user_id => id)
end

If you have a relationship between users and role_assignments (and if you don't, why not?), you can simply do this instead:

# If user :has_one :role_assignment
def assign_role_after_sign_up  
  create_role_assignment(:role_id => 1)
end

# If user :has_many :role_assignments
def assign_role_after_sign_up  
  role_assignments.create(:role_id => 1)
end

Create an after_create callback in the User model that creates and saves a role for the newly created user.

More information about callbacks is available in the Ruby on Rails guides .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM