Adding the created_at DESC Function to Rails

I have an app with comments and comments. In my action / index view, I repeat the message and display it from the most recent created to the old created at. My comments are embedded in my posts, so in my view / view I want to iterate, although the comments also get them to show from the recently created to the oldest created on. It seems I can make this work if I create a method in my post.rb file. I have it:

post.rb:

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

In my view of the post view, I can iterate over the comments for the post, and it works fine:

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

BUT I want to install this functionality at the controller level, but I cannot figure out how to do this. This is what I have in the show action in the message 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 to show:

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

@post var exists because of my action before the action. So my question is: why don't I have access to this ivar in my view after the show, just calling it in my view?

+6
source share
5 answers

With Rails updates, you can avoid using the created_at DESC SQL syntax with something like this:

@comments = @post.comments.order(created_at: :desc)

+8
source

You can use area

 class Comment < ActiveRecord::Base scope :newest_first, order(created_at: :desc) end 

then you use it as

 @comments = Comment.newest_first 

And @comments will be ordered

+7
source

you can define the order in the post model:

 class Post has_many :comments, :order => 'created_at DESC' # ... end 
+1
source

At the moment, your show action code is like returning all comments, instead of the comments associated with the message. To access @post in the view, you need to update the show action as follows.

  def show @post = Post.find(params[:id]) @comment = @post.comment.new @comments = @post.comments.order("created_at DESC") end 

This way you can access @post and @comments in Show view.

Now update the post to show comments:

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

In addition, you can also use the user @post object, if necessary. @comments for a new comment.

You can see this commentary application in the Rails guides http://guides.rubyonrails.org/getting_started.html#showing-posts Other useful links: http://www.reinteractive.net/posts/32-ruby-on- rails-3-2-blog-in-15-minutes-step-by-step

+1
source

use this in your comment model for a given default order:

 default_scope { order("created_at DESC") } 
0
source

All Articles