Alex Rivera | Logout

Rails scope find with current user

Asked 2011-11-18T17:00:07.223
18

I'm using Rails 3 with Devise for user auth. Let's say I have a User model, with Devise enabled, and a Product model, and that a User has_many Products.

In my Products controller I'd like my find method to be scoped by current_user, ie.

@product = current_user.products.find(params[:id])

unless the user is an admin user, i.e. current_user.admin?

Right now, I'm running that code in almost every method, which seems messy:

if current_user.admin?
  @product = Product.find(params[:id])
else
  @product = current_user.products.find(params[:id])
end

Is there a more elegant/standard way of doing this?

Edit
Report

1 Answer

25

I like to do this as follows:

class Product

  scope :by_user, lambda { |user|
    where(:owner_id => user.id) unless user.admin?
  }

end

this allows you to write the following in your controller:

Product.by_user(current_user).find(params[:id])
answered 2011-11-18T22:47:18.730

Your Answer