大佬教程收集整理的这篇文章主要介绍了ruby-on-rails – 构造一个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).
以上是大佬教程为你收集整理的ruby-on-rails – 构造一个Rails ActiveRecord where子句全部内容,希望文章能够帮你解决ruby-on-rails – 构造一个Rails ActiveRecord where子句所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。