Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby

Roles or Groups and Devise

I'm working on my own project and i use Devise as a way for users to register on my site. I plan on adding a section on my site where i have premium content just like Treehouse has Basic and Pro content. I've been struggling to get this to work for some time now. My guess is that i've missed some basic step because i'm really new at this :) and Devise can be somewhat complicated sometimes.

I've been looking at different gems that could help me with this. I've looked into Cancan and also Pundit. But to get those to work i need to add some kind of roles to my user model. I have tried to add boolean properties to my user model that are called "basic" , "pro" , "admin" and this is where i'm stuck. I don't seem to be able to pick up the role value and use it in Cancan or Pundit. I've been trying to use @current_user.try(:basic?) & current_user in different forms and so on and i don't seem to get it to work.

Anyone having experience with this and what common pitfall there are when you try to implement this the first time. Do i need to define some role stuff in the application controller? do i need to implement some kind of helper methods to make it work?

Treehouse should make a workshop or a course that builds on the Rails Auth course that explains how to set this up from scratch :)

5 Answers

Brandon Barrette
Brandon Barrette
20,485 Points

You should have 1 column in your user table called role. Then you can create helpers for current_user.admin?, current_user.basic? and so on.

If you are using Rails 4, the enum property was just added to Rails 4.1, which makes it easy to define the roles in the user.rb model, then you get automatic helpers like user.admin? for free. See here:

http://stackoverflow.com/questions/23192516/how-to-use-enumrails-4-1

I also recommend Pundit over CanCan.

Brandon Barrette
Brandon Barrette
20,485 Points

You use an integer column if using enum, otherwise a string column to store "admin", "basic", etc...

Gonna try this out!

If i use enum in Rails 4.1 should i still create a role column?