Just a question related to Rails best practices:
Say we have a Post and a Comment model. The same partial is used to render the post on both the index view and the show view. Inside that partial is a reference to another partial that renders the comments.
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
comments/_list.html.haml
- comments.each do |c|
c.comment
Let's now say that for the post index view, we only want to display the last 3 comments for each post, yet on the show view we want to display all comments for the post. Because the same partial is used, we can't edit the call to limit the comments. What's the best way to achieve this? Currently I've abstracted this out to a helper, however it feels a little dodgy:
def limited_comments(comments)
if params[:controller] == 'posts' and params[:action] == 'show'
comments
else
comments.limit(3)
end
end
Which means _post.html.haml is changed to read
= render 'comments/list', :comments => limited_comments(post.comments)
It works, but doesn't feel like the Rails way. I'm guessing there's a way with scopes, but I can't seem to figure it out.