开发者

How can I access "roles" in "views" in my Rails app?

开发者 https://www.devze.com 2023-01-17 05:25 出处:网络
In the Rails 3 app that I\'m building to help me learn Ruby on (and) Rails, I\'m a bit confused by the \"roles/roles_users/users\" tables.

In the Rails 3 app that I'm building to help me learn Ruby on (and) Rails, I'm a bit confused by the "roles/roles_users/users" tables.

I have Devise and CanCan and I want to "access" these roles.

Right now, I have three roles:

admin

staff

client

In the database, I have these tables (and a few others):

roles (table)

id => 1 || name => admin

id => 2 || name => staff

id => 3 || name => client

roles_users(table)

role_id => 1 || user_id => 1

role_id => 2 || user_id => 2

role_id => 3 || user_id => 3

users(table)

user1

user2

user3

So right now I have three users. User #1 is "admin", User #2 is "staff", and User #3 is "client."

In "views/admin/users/开发者_开发问答show.html.erb", I would like to display each user's "role" and then also allow the admin to change it. Once I am able to display the role, I think I can set it up so that admin can change it.

The thing is...I'm a bit confused as to which variable/name I can use to show each user's role. I can easily access things like user.first_name or user.address, but I'm unsure how I can access something like user.role (which doesn't work).

Any suggestions?

Cheers!

Sam


I guess you can do @user.roles. The thing is, I guess each user only has one role (although it's a hmabtm relationship), so you could create in your user model:

def role
  roles.first
end

def role=(role_id)
  self.roles = [Role.find(role_id)]
end


The convention of CanCan is to create a role? method. I know you only have one role per user, but this will work for you if you decided later to have multiple roles per user:

def role?(role)
  !!self.roles.find_by_name(role.to_s)
end

The !! is a way to coerce anything into a boolean.

This way you can check for authorization with:

if user.role? :editor
  can :manage, Foo
end

Read: if the user has a role of editor then they can manage the Foo model.


@user.roles # returns a collection of roles for the given user


try: @user.roles.first.name

0

精彩评论

暂无评论...
验证码 换一张
取 消