How to implement the inversion of the output of comments from the database? In other words, the last added comments (and other data) were not displayed at the end of the page, but were placed up the list? code:

<% posts.each do |post| %> <h3><% post.comment %></h3> 

    2 answers 2

    Usually when outputting from a database, the data is sorted by one or more columns. If the comment table has a created_at calendar column, you can sort it by reverse order. To do this, it must be supplied with the desc keyword (so that in the SQL query the reverse sorting SELECT * FROM posts ORDER BY created_at DESC )

     posts = Post.order('created_at desc') 

    The latest versions of RoR support character format.

     posts = Post.order(created_at: :desc) 
    • A small remark. From the point of view of architecture, it is better to remove it in skoup. - anoam

    If you need to sort by this principle often, you can set the sort in scope

     scope :order_desc, -> { order(created_at: :desc) } 

    After you have defined the scope in the model, you can define all the posts in the variable in the desired order:

     posts = Post.order_desc 
    • Manipulations with the default skoup better not to do. This can have hard-to-predict consequences. - anoam
    • ... and if we advise him to change, then explain why this is an extreme measure and when it can be useful. And how to get around it on occasion. - D-side
    • Another thing. And the cherry b on the cake: an example of use. - D-side
    • Already better! It remains to correct the syntax error. Unless, of course, nothing new will arise ._. - D-side
    • Thank you for the comments. - Alexander Shvaykin