假设我在控制器中有一个方法:
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)
来获得我需要的东西?
答案 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