psharma
psharma

Reputation: 1289

Restrict devise users to their own view/association

I am using devise for authentication and have an association between users (has_many :products) and products model (belongs_to :user).

My routes file is

resources :users do 
  resources :products
end

Now what happens is, user with id 3 at /users/3/products can also see whats at /users/4/products. I want to restrict that. I dont want /users/3/products to able to see whats at /users/4/products and so on (not specific to these two users but for all). How do I do it ? Should I have a Users Controller? I dont have it right now. If i have the controller, how do I do it? I was thinking maybe redirect it?

thanks

Upvotes: 2

Views: 1543

Answers (1)

mind.blank
mind.blank

Reputation: 4880

You could add a before_filter in your products controller:

class ProductsController < ApplicationController
  before_filter :user_is_current_user
  ...
  private

  def user_is_current_user
    unless current_user.id == params[:user_id]
      flash[:notice] = "You may only view your own products."
      redirect_to root_path
    end
  end
end

Also, in the products controller you could retrieve only products belonging to the current_user:

def index
  @products = current_user.products # will fetch all products with a user_id matching the current user's
end

If you used the above you wouldn't really need a user's ID in the URL, you could use a path like /users/products or just /products.

Upvotes: 3

Related Questions