Rails scope find with current user

后端 未结 3 465
失恋的感觉
失恋的感觉 2021-02-01 20:43

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

3条回答
  •  别跟我提以往
    2021-02-01 21:39

    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])
    

提交回复
热议问题