2016-05-09 65 views
0

我正在重写查询以提高可读性。原来,这一切都是在同一行:Rails ActiveRecord查询语法问题 - 不返回任何记录

@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) 

我想多行拆分这一点,我也跟着上分裂Ruby代码分成多行过去StackOverflow的答案: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 (?)", "%"[email protected]+"%", "%"[email protected]+"%"]). 
    page(params[:page]).per(4) 

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

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

+1

如果追加'.to_sql'到的每个版本这个查询,你看到了什么?查询如何不同? –

+0

第二个查询还包含'where'条件:'listing_agent__c:@ userId',它不存在于第一个查询中... – BoraMa

+0

同样对于一般的美化,有几个很好的理由可以限制每行80个字符。这不仅仅是代码的外观 - 这种纪律是一位好老师。它会照亮你的代码太复杂,嵌套过深的地方,等等。 –

回答

0

好像你已经解决了你的问题。

既然你的目的为提高可读性,我想目前我怎么会结构查询(如果我没有被允许使用范围):

@properties = Listing.where(
    baths__c:   @baths, 
    bedrooms__c:   @beds, 
    sales_price__c:  (@[email protected]), 
    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)