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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 构造一个Rails ActiveRecord where子句前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用Rails ActiveRecord构建where子句的最佳方式是什么?例如,假设我有一个控制器操作返回博客帖子列表:
  1. def index
  2. @posts = Post.all
  3. end

现在,我想说,我想要传递一个url参数,以便这个控制器操作只返回一个特定的作者的帖子:

  1. def index
  2. author_id = params[:author_id]
  3.  
  4. if author_id.nil?
  5. @posts = Post.all
  6. else
  7. @posts = Post.where("author = ?",author_id)
  8. end
  9. end

这对我来说并不感觉很干燥.如果我添加排序或分页,或者更糟的是,更多可选的URL查询字符串参数过滤,这个控制器的操作会变得非常复杂.

解决方法

怎么样:
  1. def index
  2. author_id = params[:author_id]
  3.  
  4. @posts = Post.scoped
  5.  
  6. @post = @post.where(:author_id => author_id) if author_id.present?
  7.  
  8. @post = @post.where(:some_other_condition => some_other_value) if some_other_value.present?
  9. end

Post.scoped本质上是一个相当于Post.all的惰性加载(因为Post.all返回一个数组立即,Post.scoped只返回一个关系对象).此查询将不会执行你实际上试图在视图中迭代它(通过调用.each).

猜你在找的Ruby相关文章