使用Rails ActiveRecord构建where子句的最佳方式是什么?例如,假设我有一个控制器操作返回博客帖子列表:
- def index
- @posts = Post.all
- end
现在,我想说,我想要传递一个url参数,以便这个控制器操作只返回一个特定的作者的帖子:
- def index
- author_id = params[:author_id]
- if author_id.nil?
- @posts = Post.all
- else
- @posts = Post.where("author = ?",author_id)
- end
- end
这对我来说并不感觉很干燥.如果我添加排序或分页,或者更糟的是,更多可选的URL查询字符串参数过滤,这个控制器的操作会变得非常复杂.
解决方法
怎么样:
- def index
- author_id = params[:author_id]
- @posts = Post.scoped
- @post = @post.where(:author_id => author_id) if author_id.present?
- @post = @post.where(:some_other_condition => some_other_value) if some_other_value.present?
- end
Post.scoped本质上是一个相当于Post.all的惰性加载(因为Post.all返回一个数组立即,Post.scoped只返回一个关系对象).此查询将不会执行你实际上试图在视图中迭代它(通过调用.each).