加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:43:26 所属栏目:百科 来源:网络整理
导读:使用Rails ActiveRecord构建where子句的最佳方式是什么?例如,假设我有一个控制器操作返回博客帖子列表: def index @posts = Post.allend 现在,我想说,我想要传递一个url参数,以便这个控制器操作只返回一个特定的作者的帖子: def index author_id = params
使用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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读