heartcombo/has_scope

default option doesn't work

danielgatis opened this issue · 7 comments

I need to scope my models with the current logged user. So i did the following:

  #didnt work
  has_scope :by_owner, default: ->(controller){ controller.current_user }

  #didnt work
  has_scope :by_owner, allow_blank: true, default: ->(controller){ controller.current_user }

  #didnt work
  has_scope :by_owner, allow_blank: true, do |controller, scope, value|
    scope.by_owner(controller.current_user)
  end

So i changed the code to this and it works:

  has_scope :by_owner, allow_blank: true,
                       default: ->(controller){ controller.current_user } do |controller, scope, value|
    scope.by_owner(controller.current_user)
  end

this is right? What's the best approach?

@danielgatis can you please provide more info on how it doesn't work? Thanks.

@danielgatis I mean is there an error or something like that? It would be great if you can provide a simple app that reproduces your issue since your app looks kinda big and I think it's not that easy to setup it and reproduce your problem.

has_scope :by_owner, default: ->(controller){ controller.current_user }

The default value is set to nil when 'parse_value' method is called.

  def parse_value(type, key, value) #:nodoc:
    if type == :boolean
      TRUE_VALUES.include?(value)
    elsif value && ALLOWED_TYPES[type].any?{ |klass| value.is_a?(klass) }
      value
    end
  end

To fix was override ALLOWED_TYPES to include my User class, so at my initializers folder i created has_scope.rb

module HasScope
  ALLOWED_TYPES = {
    :array   => [ Array ],
    :hash    => [ Hash ],
    :boolean => [ Object ],
    :model => [ ActiveRecord::Base ],
    :default => [ String, Numeric ]
  }
end

and updated my controller code to

has_scope :by_owner, default: ->(controller){ controller.current_user }, type: :model

Well, as for me it makes sense that default doesn't work this way since you can't pass an object (current_user in your case) through http params.

yep! i agree.

@danielgatis ok, I'm closing this then.