There Are Four Lights
There Are Four Lights

Reputation: 1426

Best way to check user's permission by id?

In Rails3 application i have a number of models with user_id - this way i'm saying: it was created by some user.

Like:

current_user.id #=> 1
@item.user_id #=> 1
# this item created by user with id 1

And i want to restrict current_user's acess to items which was not created by him/her.

Something like:

if @item.user_id == current_user.id
  #everything is fine
else
  #redirect somwhere with flash "You don't have an access here"
end

What is the best way for this, because i have multiple number of models (and controllers to show/edit/destroy) with such a user_id?

Upvotes: 3

Views: 251

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

Use CanCan!

With it you will be able to define permissions declaratively, like this:

can :read, Project, :user_id => user.id

And later enforce this rule:

def show
  @project = Project.find(params[:id])
  authorize! :read, @project
end

authorize! will raise an exception, but you can check in a more peaceful manner:

<%= link_to 'Link to a project', @project if can? :read, @project %>

You can intercept authorization errors and handle them in one place:

class ApplicationController < ActionController::Base
  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_url, :alert => exception.message
  end
end

Upvotes: 4

Matthew Rudy
Matthew Rudy

Reputation: 16834

The simplest way to do this, is to use Active Record's has_many.

Namely, in a controller, whenever you load the Item, you just say

@item = current_user.items.find(params[:id])

This way you don't have to do any work to check.

Upvotes: 0

Related Questions