使用 Rails ActiveRecord 构造 where 子句的最佳方法是什么?例如,假设我有一个返回博客文章列表的 Controller 操作:
def index
@posts = Post.all
end
现在,假设我希望能够传入一个 url 参数,以便此 Controller 操作仅返回特定作者的帖子:
def index
author_id = params[:author_id]
if author_id.nil?
@posts = Post.all
else
@posts = Post.where("author = ?", author_id)
end
end
这对我来说不是很干燥。如果我要添加排序或分页,或者更糟糕的是,更多可选的 URL 查询字符串参数来过滤,这个 Controller 操作会变得非常复杂。
最佳答案
嗯,您想使用的最佳方法是通过 2 个 Action 来传播它
def index
@post = Post.all
end
def get
@post = Post.where("author=?", params[:author_id])
end
恕我直言,如果您考虑使用 RESTful API,则更有意义,索引意味着列出所有并获取(或显示)以获取请求的 API 并显示它!
关于ruby-on-rails - 构建 Rails ActiveRecord where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5820277/