ruby-on-rails – 构造一个Rails ActiveRecord where子句

使用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).

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...