2

为我的 application_controller 编写代码以将用户输入转换为查询,这是有效的:

result_set =  model  # some implementation of ActiveRecord::Base as a Class
.includes(:metric_template => [:group]) #still need to abstract this
.where(f)  
.order(sort_string)
.limit(rows)
.offset((page-1)*rows)

这不起作用,因为似乎没有调用 where 方法:

result_set =  model
.includes(:metric_template => [:group])  #still need to abstact this
.tap{|o| o.where(f) if f}
.order(sort_string)
.limit(rows)
.offset((page-1)*rows)

我真的很想 .tap() 在这里工作。为什么不呢?它不能作为类方法使用吗?可以说服吗?

感谢任何指导。

4

2 回答 2

2

where被调用就好了。问题是它where没有任何可见的副作用 - 它仅用于其返回值。

由于tap不对块的返回值做任何事情,因此tap与没有可见副作用的块一起使用是没有意义的。

于 2012-07-10T01:10:10.447 回答
1

这就是你(实际上)想要的:

result_set = model.
  includes(:metric_template => [:group]).  #still need to abstact this
  order(sort_string).
  limit(rows).
  offset((page-1)*rows)
result_set = result_set.where(f) if f

这并不是真正需要 的情况tap,这对于在不更改方法的返回值的情况下对方法内的项目进行操作最有用(出于 sepp2k 已解释的原因)。

此外,最好将此查询移动到模型内的方法中。

于 2012-07-10T02:41:13.307 回答