Adding created_at DESC functionality in Rails

Viewed 20972

I have an app with post and comment models. In my index action/view, I am iterating through the post and displaying them from most recently created at to oldest created at. My comments are nested inside my posts so in my post show action/view, I want to iterate though the comments and get them to show from most recently created at to oldest created at. I can only seem to get this to work if i create a method in my post.rb file. I have this:

post.rb:

  def newest_comments
    self.comments.order("created_at DESC")
  end  

In my post show view, I can iterate through the post comments and it works great:

<% @post.newest_comments.each do |comment|
<% end %>

BUT I want to set this functionality in the controller layer, but I can't figure out how. This is what I have in the show action in my posts controller:

  def index
    @posts = Post.all.order("created_at DESC")
  end

  def show
    @comment = Comment.new
    @comments = Comment.all.order("created_at DESC")
  end

And now my updated post show view:

<% @post.comments.each do |comment| %>
<% end %>

The @post var is there because of my before action. So my question is, why do I not have access to this ivar in my post show view by simply calling this in my show view?

5 Answers
Related