state_machines-activerecord
state_machines-activerecord copied to clipboard
scope used on search application
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\""