Ruby代码美化,将长指令分割成多行

47

我们如何编写以下语句以提高可读性?

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])
3个回答

61

也可以这样做

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)

反斜杠这个东西非常有用!谢谢 - Kristiyan Tsvetanov

55

像这样做:

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版本中编译。在之前的版本中确实是无效的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接