Taking a break from Java with Rails role management

Its being so long since I have written a new post..

Being working on a little something lately that entails Rails and the Ruby language. Ruby on Rails is a very interesting platform for creating web applications. It provides many tools out of the box that require little or no configuration to work. It is a bit to awkward to begin with for a Java person but this goes away with usage. I have some questions regarding performance but I guess I am going to find out about it one way or another :D.

One of the basic stuff that one comes across when trying to create a new relatively complex application is the user, role management. I guess that this is something platform independent and as long as you use the database for that kind of thing you are always going to come up with a schema of the kind:

user(id, name, etc...)
role(id, name) # one role is Manager

Where Managed is a little something that is managed by the user when he has a specific role.
To be complete, one must use an extra association table that will contain all possible (User, Role, Managed) triples. This is:

user_role_managed(id, user_id, role_id, managed_id)

Q: How I am going to use these tables DIRECTLY from my web page in Rails, when I want to display specific HTML elements for specific users/roles?

A: Well in rails there are these beautiful constructs named helpers:

def is_manager? user, managed
    UserRoleManaged.exists?(:user_id => user.id, :managed_id => managed.id, :role_id => Role.find_by_name('Manager').id)

which can be referenced like this from the view:

< %= link_to 'Delete Managed', delete_managed_path(@managed) if is_manager_of @user, @managed %>

Of course many things are not said here, but I think that the overall simplicity is obvious. As long as you have setup your model, creating the helper and using it from the view is quite straightforward.

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.