Creating the Role model

41 views
Skip to first unread message

Melanie M

unread,
Mar 25, 2014, 9:55:03 PM3/25/14
to declarative_...@googlegroups.com
Hi,

I am trying to implement Declarative Authorization in my rails 4 app. I think my questions are possibly too simple to have been addressed in the documentation.

I have a user model (which has many roles) and a role model (which belongs to user).  

The role model has a single attribute (string: name).

The user model includes the following method:

  def role_symbols 
  roles.map do |role|
      role.name.underscore.to_sym
    end

The role permissions are defined in authorization_rules.rb.

My questions are:

1. Should I have more attributes in my role model? I specifically wondered whether it was sensible to have boolean attributes for each role defined in the authorization_rules.rb file so that I can then mark the relevant role as true when a user is created.

2. What is the best way to go about allocating roles to users? If the boolean logic I describe above is not the best way, I would very much welcome tips on how to approach this.

Many thanks,
Melanie

Xavier B

unread,
Jun 25, 2014, 8:47:12 AM6/25/14
to declarative_...@googlegroups.com
Hi Melanie,

Sorry for the late response.  I hope it is still useful.  The way I handle roles is almost identical to what you are doing, except that I use a has_and_belongs_to_many relationship between users and roles.  That way I can limit the number of role objects to only the number of levels of authorization I need.  They have a single attribute, title in my case.  I also define role_symbols in a way that can handle the case where a user has no roles. I use rails_admin to assign roles to users, but you can easily use any type of data management system. For the first admin user on my app in production I think I just opened a rails console on my server typed something like u = User.find(1) / u.roles << Role.find_by_title('admin') / u.save.  For my role_symbols definition, mine is essentially the same as yours but I use (roles || []).map to handle the case in which a user has no roles.
Reply all
Reply to author
Forward
0 new messages