【问题标题】:Scope in Rails 5 for string match returning wrong sql queryRails 5 中字符串匹配返回错误 sql 查询的范围
【发布时间】:2017-08-07 19:37:46
【问题描述】:

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

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

现在当这个范围被调用并且传递的用户输入的参数为空时,生成的sql查询是

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

我该如何解决这个问题?

【问题讨论】:

  • 我希望范围仅在参数不为空时运行
  • 如果是nil,预期的行为是什么?
  • 如果范围为空,则根本不应调用。我有类似的整数匹配范围,可以按预期工作。

标签: ruby-on-rails activerecord


【解决方案1】:

用括号括住您的 where 函数调用:

where(retro: retro) if retro.present?

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

【讨论】:

  • 你确定是这个scope放了where子句吗?
【解决方案2】:
scope :category, ->(retro) { where(retro: retro) if retro.present? }

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

【讨论】:

  • 谢谢你,这有效。我用括号弄错了。
【解决方案3】:

在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多