只是一个与 Rails 最佳实践相关的问题:
假设我们有一个 Post 和一个 Comment 模型。相同的部分用于在索引视图和显示视图上呈现帖子。在该部分内部是对呈现评论的另一个部分的引用。
post_controller.rb
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
_post.html.haml
.post
= post.content
= render 'comments/list', :comments => post.comments
评论/_list.html.haml
- comments.each do |c|
c.comment
现在假设对于帖子索引视图,我们只想显示每个帖子的最后 3 条评论,但在显示视图中我们希望显示帖子的所有评论。因为使用了相同的部分,我们不能编辑调用来限制评论。实现这一目标的最佳方法是什么?目前我已经将它抽象为一个助手,但是感觉有点狡猾:
def limited_comments(comments)
if params[:controller] == 'posts' and params[:action] == 'show'
comments
else
comments.limit(3)
end
end
这意味着_post.html.haml更改为读取
= render 'comments/list', :comments => limited_comments(post.comments)
它有效,但感觉不像 Rails 方式。我猜有一种使用范围的方法,但我似乎无法弄清楚。