2011-09-09 18 views
35

我們如何編寫以下語句來提高可讀性?紅寶石代碼美化,在多行上拆分長指令

Promotion.joins(:category).where(["lft>=? and rgt<=?", c.lft, c.rgt]).joins(:shops).where(:promotions_per_shops => { :shop_id => shops_id }).count('id', :distinct => true) 

以下不編譯

Promotion.joins(:category) 
     .where(["lft>=? and rgt<=?", c.lft, c.rgt]) 
     .joins(:shops) 
     .where(:promotions_per_shops => { :shop_id => shops_id }) 
     .count('id', :distinct => true) 

syntax error, unexpected '.', expecting kEND 
        .where(["lft>=? and rgt<=?", c.lft, c.rgt]) 

回答

44

做這樣的:

Promotion.joins(:category). 
     where(["lft>=? and rgt<=?", c.lft, c.rgt]). 
     joins(:shops). 
     where(:promotions_per_shops => { :shop_id => shops_id }). 
     count('id', :distinct => true) 
14

應該在1.9編譯。在以前的版本中確實是無效的。

48

也可以做

Promotion.joins(:category) \ 
     .where(["lft>=? and rgt<=?", c.lft, c.rgt]) \ 
     .joins(:shops) \ 
     .where(:promotions_per_shops => { :shop_id => shops_id }) \ 
     .count('id', :distinct => true) 
+0

的 '\' 的事情是非常有幫助!謝謝 –