ruby-on-railsscopedefault-scope

Can a default scope take arguments in rails?


I want to create a default scope to filter all queries depending on the current user. Is it possible to pass the current user as an argument to the default_scope? (I know this can be done with regular scopes) If not, what would be another solution?


Solution

  • Instead of using default_scope which has a few pitfalls, you should consider using a named scope with a lambda. For example scope :by_user, -> (user) { where('user_id = ?', user.id) }

    You can then use a before_filter in your controllers to easily use this scope in all the actions you need.

    This is also the proper way to do it since you won't have access to helper methods in your model. Your models should never have to worry about session data, either.

    Edit: how to use the scope in before_filter inside a controller:

    before_filter :set_object, only: [:show, :edit, :update, :destroy]
    
    [the rest of your controller code here]
    
    private
    def set_object
       @object = Object.by_user(current_user)
    end
    

    obviously you'd change this depending on your requirements. Here we're assuming you only need a valid @object depending on current_user inside your show, edit, update, and destroy actions