在RoR中添加额外的过滤器参数

时间:2012-12-21 05:51:07

标签: ruby-on-rails ruby

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

 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

其中some_extra_filter可以是lambda,或者只是一个普通的sql“,其中”string也可以是nil或“”。

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

1 个答案:

答案 0 :(得分: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