2

I am working on a Ruby on Rails 3 web application.

I have a table named User with a coulmn named role. I am looking for the best way to hide parts of the view from users that have the "wrong" role for those parts of the view.

For example I want all users to be able to see the users index page, but i want only users with a role - admin to be able to edit other users.

So first I block the edit action using filter_by, but what I also want is make the edit button not to appear.

The current user is saved in the session, so checking the user role is very simple.

What I am asking, is there an easy way to do so besides the obvious if statement before each button I want to hide. I would think that rails would have an easy way to do this type of thing, I couldn't find one.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Nachshon Schwartz
  • 15,289
  • 20
  • 59
  • 98

2 Answers2

3

You may want to use Devise and CanCan.

Here is a RailCast tutorial

Nerian
  • 15,901
  • 13
  • 66
  • 96
  • Thanks, but I am looking for more of a default built in type answer. – Nachshon Schwartz Jan 18 '11 at 00:25
  • 1
    @nayish There is nothing "built in" to Ruby or Rails for this. You can write your own authorization system or use an existing one, like CanCan, which Nerian linked. – Jimmy Jan 18 '11 at 01:33
2

if you wanted to clean it up a tiny bit you could write yourself an application helper:

  def if_admin(user)
    if(user.is_admin? && block_given?)
      yield
      return
    end
  end

then in your view you could write:

  <% if_admin(@user) do %>
    <some admin only html />
  <% end %>
greggreg
  • 11,945
  • 6
  • 37
  • 52
  • 1
    There's no `user` argument to that method and it's more performant not to capture the block as an argument. You'd probably want to do it like this: `def display_if_admin(user); yield if block_given? && user.admin?; end;` – Jimmy Jan 18 '11 at 02:26
  • Then what `user` would the function use? Where do i set the specific user? – Nachshon Schwartz Jan 18 '11 at 02:38
  • @nayish you pass the user object that you grab in your controller to the `if_admin()` method in the view. The `is_admin?` method would be defined in your User model class. – greggreg Jan 18 '11 at 03:00
  • would this method be available for use in any view including out of the User view? – Nachshon Schwartz Jan 18 '11 at 03:06
  • yes if you put it in `application_helper.rb`. Any other helper and it will only be automatically available to that helper's corresponding controller. You will need to always have the user object to pass to it though. – greggreg Jan 18 '11 at 03:27
  • I wish there was a better way to do this. What if there are 8 different possibilities? Like, if_admin, if_moderator, if_banned, if_warned, if_logged_in, etc. etc. – hrdwdmrbl Jan 31 '13 at 16:12