Search code examples
ruby-on-railsruby-on-rails-4has-scope

.current_user not working when using scopes?


I'm using Devise and has_scope gem for filtering options and only want show a current users links only.

This works

@links = current_user.links.all


This does not. Can someone explain what i need to do to make this work?

@links = apply_scopes(Link).current_user.all

Solution

  • One solution is to create a scope in the link that takes an argument user_id and in your controller has_scope with no arguments, and just pass a hash to apply_scopes method to override the supplied values of your scope.

    Link Model

    scope :of_user,->(user_id){ where(user_id: user_id)}
    

    Link Controller

    has_scope :of_user
    

    Just call apply_scopes(Link, of_user: current_user.id).all where of_user is just the applied params for the named scope.