Adding methods to models

This is more of a theoretical question I suppose - I’m looking for what
consensus is for the “correct” approach in Rails/MVC.

I have a standard security model where a User can have many Roles. There
a User model, a Role model, and in the db, a linking table, etc. Each
has a name as well as a category (say, name=“waiter”,
worker”, for example).
I can check to see of a user has a particular role by doing something
the lines of


There is probably a shorter way of doing this, but the point is this:
Would it be “correct” in the Rails/MVC world to add a method to the User
model so that you could do

@session[:user].has_role_category?(“restaurant worker”)

(with a better name, of course :slight_smile:
Any downside to taking this approach? Is there a “better” one that I


I would say if it improves code readability you should always add a
method. In your example it’s arguable whether that’s the case (both
seem pretty readable to me). I wouldn’t do it for the sake of it.

On Friday 16 December, Keith L. wrote:

@session[:user].roles.include?(Role.find_by_category(“restaurant worker”))

Look up the law of demeter. I forget the exact wording, but the way
I think of it is something like this: “it’s okay to play with your
friends, and it’s acceptable to play with your friends’ friends, but
that’s it”.

In other words, it’s okay for a user to know about methods on a role
object, but you shouldn’t really go further afield than that without
wrapping stuff up in methods.

I find this approach reduces the number of things that need changing
when something needs refactoring, which is great as anything that puts
you off refactoring is likely to reduce the readability of your code.

It also makes the code you write easier to understand.

@session[:user].has_role_category?(“restaurant worker”)

This one leaves little room for doubt about it’s intent, and is
therefore preferable in my opinion.

The user should be responsible for itself. Your second approach is the
object-oriented way.

Although you might even ask it to report its actual category, not
whether it
is a certain kind.

e.g. session[:user].role >> ‘restaurant worker’

  • Rabbit

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs