views:

31

answers:

1

The scenario is this:

I have some users on my site. A user has a role, the relevant ones here is admin and normal. I also have a model, let's call it SomeModel.

I have created a backend for the site, which uses an admin layout. All admins have full access to edit any content.

The problem arises with this relation: User -> owns -> SomeModel. That means a non admin User can own an instance of SomeModel and should be able to edit the data of this instance.

The controller for SomeModel has an edit action which then caters to both admins and regular users.

However, I don't want regular users seing the admin layout and right now, the way I do this is like so:

if current_user.admin?
  render :layout => 'admin'
end

Which defaults to the standard layout if the user is not an admin. I have this in all my actions for SomeModel and it just doesn't seem like a very Rails way of doing things.

Is there a better way?

+1  A: 

You can do this at the controller level:

  class MyModelController < ActionController::Base
    layout :user_or_admin_layout

    def index
      # fetching objects
    end

    private
      def user_or_admin_layout
        current_user.admin? ? "admin_layout" : "user_layout"
      end
  end

There are more examples in the rails documentation for layout

Jeff Paquette
Thanks for the link. I think I skipped over that part of the documentation, this definitely feels "cleaner".
rhardih