Rails 5中的范围用于字符串匹配返回错误的sql查询

时间:2017-08-07 19:37:46

标签: ruby-on-rails activerecord

我在Rails 5中有一个范围,用于检查是否存在字符串值。

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

现在调用此作用域并且传递的用户输入的参数为null时,生成的sql查询是

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

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

用括号括起where函数调用:

where(retro: retro) if retro.present?

if正在应用于参数而不是方法调用。

答案 1 :(得分:0)

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

如果没有括号,则假设您希望if成为SQL的一部分

答案 2 :(得分:0)

在Rails4中,您可以使用以下格式。我想这同样适用于Rails5

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

scope :category

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

参考链接

Rails 4 - Do not scope if conditions