【问题标题】:Rails ActiveRecord query syntax issue - not returning any recordsRails ActiveRecord 查询语法问题 - 不返回任何记录
【发布时间】:2016-05-09 18:54:33
【问题描述】:

我正在重写一个查询以提高可读性。原来都是一行:

@properties = Listing.where(website_approved__c: 'true').where(status__c: 'Active').where("sales_price__c >= ?", @pricemin ).where("sales_price__c <= ?", @pricemax ).where(bedrooms__c: @beds ).where(baths__c: @baths ).where("lower(city__c) LIKE (?)", "%" + @city.downcase + "%").where("zip_code__c LIKE (?)", "%" + @zip + "%").page(params[:page]).per(4)

我想将其拆分为多行,我遵循了过去 StackOverflow 关于将 Ruby 代码拆分为多行的答案:Ruby code beautification, split long instructions on multiple lines

这是我写的:

@properties = Listing.where(website_approved__c: 'true', status__c: 'Active', bedrooms__c: @beds, baths__c: @baths).
    where([ "sales_price__c >= ? AND sales_price__c <= ?", @pricemin, @pricemax]).
    where(["lower(city__c) LIKE (?) AND zip_code__c LIKE (?)", "%"+@city.downcase+"%", "%"+@zip+"%"]).
    page(params[:page]).per(4)

但是,新查询将永远不会返回任何内容。我保持 WHERE 子句相同,这就是为什么我想知道这是否是语法问题。有人能解释一下吗?

我目前正在运行 Rails v4.2.1。

【问题讨论】:

  • 如果您将.to_sql 附加到此查询的每个版本,您会看到什么?查询有何不同?
  • 第二个查询还包含where 条件:listing_agent__c: @userId,这在第一个查询中不存在...
  • 为了一般的美化,有几个很好的理由将自己限制为每行 80 个字符。这不仅仅是关于代码的外观——这种纪律是一位好老师。它将照亮您的代码过于复杂、嵌套过深等的地方。
  • @BoraMa 抱歉,我不小心从其他来源复制并粘贴了。修正了原来的问题。
  • 现在查询似乎和我一样,为了证明,我也会比较他们的to_sql 版本,就像上面@CarlTashian 建议的那样。

标签: ruby-on-rails ruby activerecord


【解决方案1】:

看来您已经解决了问题。

由于您的目标是提高可读性,我想介绍一下我将如何构建该查询(如果不允许我使用范围):

@properties = Listing.where(
  baths__c:            @baths,
  bedrooms__c:         @beds,
  sales_price__c:      (@pricemin..@pricemax),
  status__c:           'Active', 
  website_approved__c: 'true'
).where(
  'lower(city__c) LIKE :city AND zip_code__c LIKE :zip', 
  city: "%#{@city.downcase}%", 
  zip:  "%#{@zip}%"
).page(params[:page]).per(4)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多