state_machines-activerecord icon indicating copy to clipboard operation
state_machines-activerecord copied to clipboard

scope used on search application

Open gagalago opened this issue 7 years ago • 0 comments

I have a controller that performs a search. To do that I have a lot of scopes chained together to obtain the right result. Because the user doesn't need to fill all scopes, when a scope is not used, the scope must be transparent. Usually, I do for example scope :in_range, ->(min, max) { where(id: (min..max)) if min.present? && max.present? } used like that:

Project.in_range(params[:min], params[:max)
           .in_country(params[:country])
           .with_job(params.dig(:job, :name), params.dig(:job, :user))

what do you think if I modify https://github.com/state-machines/state_machines-activerecord/blob/daec4b5312b6bf64f6e5d24059c25f93c081f18e/lib/state_machines/integrations/active_record.rb#L567-L569 to

        def create_scope(name, scope)
          lambda { |model, values| model.where(scope.call(values)) if values.present? }
        end

So I will change the behaviour from:

$> Project.with_states(nil).to_sql
IndexError: nil is an invalid name

to:

$> Project.with_states(nil).to_sql
=> "SELECT \"projects\".* FROM \"projects\""

gagalago avatar Dec 05 '17 07:12 gagalago