构造一个Rails ActiveRecord where子句

Kev*_*ang 17 activerecord ruby-on-rails

使用Rails ActiveRecord构造where子句的最佳方法是什么?例如,假设我有一个控制器操作,它返回一个博客帖子列表:

def index
  @posts = Post.all
end
Run Code Online (Sandbox Code Playgroud)

现在,假设我希望能够传入url参数,以便此控制器操作仅返回特定作者的帖子:

def index
  author_id = params[:author_id]

  if author_id.nil?
    @posts = Post.all
  else
    @posts = Post.where("author = ?", author_id)
  end
end
Run Code Online (Sandbox Code Playgroud)

这对我来说感觉不太干.如果我要添加排序或分页或更糟糕的是,更多可选的URL查询字符串参数进行过滤,此控制器操作将变得非常复杂.

Joh*_*ibb 24

怎么样:

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
Run Code Online (Sandbox Code Playgroud)

Post.scoped本质上是一个延迟加载等效于Post.all(因为Post.all立即返回一个数组,而Post.scoped只返回一个关系对象).在您实际尝试在视图中迭代它(通过调用.each)之前,不会执行此查询.

  • 不推荐使用范围。[这似乎相关](http://stackoverflow.com/a/18199294/673826) (2认同)