1

假设我在控制器中有一个方法:

 def my_find(is_published, count)
    items = Idea.where(published: is_published)
    #......
 end

有时我想传递一些额外的过滤器参数

 def my_find(is_published, count, some_extra_filter = nil)
    items = Idea.where(published: is_published) #.where (some_extra_filter)
    #......
 end

wheresome_extra_filter可以是lambda或只是一个普通的sql“where” string,它也可以是nil或“”。

那么我如何连接 .where(published: is_published)where (some_extra_filter)获得我需要的东西呢?

4

1 回答 1

2

这实际上很容易使用范围:

def my_find
  @items = Idea.scoped
  @items = @items.where(published: is_published) unless is_published.nil?
  @items = @items.where(other: other_param) if other_params < 10
  # etc, etc
end
于 2012-12-21T06:11:50.013 回答