我在Rails 5中有一个范围,用于检查是否存在字符串值。
scope :category, ->(retro) {where retro: retro
if retro.present? }
现在调用此作用域并且传递的用户输入的参数为null时,生成的sql查询是
'SELECT * FROM categories WHERE categories.retro IS NULL'
我该如何解决这个问题?
答案 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
参考链接