0

I have a scope in Rails 5 that checks for the presence of a string value.

scope :category, ->(retro) {where retro: retro 
if retro.present? }

Now when this scope is called and the param from user input passed is null, the sql query generated is

'SELECT * FROM categories WHERE categories.retro IS NULL'

How do I solve this?

3
  • I want the scope to run only when the parameter is not null Commented Aug 7, 2017 at 19:41
  • If it is nil, what is the expected behavior? Commented Aug 7, 2017 at 19:58
  • If the scope is null it should not called at all. I have similar scopes for integer matches which work as expected. Commented Aug 7, 2017 at 20:15

3 Answers 3

1

Surround your where function call with parenthesis:

where(retro: retro) if retro.present?

The if was being applied to the parameter and not to the method call.

Sign up to request clarification or add additional context in comments.

1 Comment

Are you sure it's this scope that's putting the where clause?
0
scope :category, ->(retro) { where(retro: retro) if retro.present? }

Without the brackets, it's assumed that you want the if to be part of the SQL

1 Comment

Thank you, this worked.I had made a mistake with the brackets.
0

In Rails4, you can use in below format. I guess same applies in Rails5

scope :category, ->(retro) {
  unless retro.blank?
    where(retro: retro)
  end
end

or

scope :category

def self.category(retro)
   unless retro.blank?
    where retro: retro
  end
end

Reference link

Rails 4 - Do not scope if conditions

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.