Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

scope used on search application #66

Open
gagalago opened this issue Dec 5, 2017 · 0 comments
Open

scope used on search application #66

gagalago opened this issue Dec 5, 2017 · 0 comments

Comments

@gagalago
Copy link

gagalago commented Dec 5, 2017

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

def create_scope(name, scope)
lambda { |model, values| model.where(scope.call(values)) }
end
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 added a commit to gagalago/state_machines-activerecord that referenced this issue Dec 5, 2017
allow to chain scopes and scopes are transparent if no values are given to it.

fix state-machines#66
diegotoral pushed a commit to diegotoral/state_machines-activerecord that referenced this issue Apr 17, 2021
allow to chain scopes and scopes are transparent if no values are given to it.

fix state-machines#66
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant