【发布时间】: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