微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/ruby/273971.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐