order_by in block each rails 3.1

14,012

order method is what you're looking for:

<% post.comments.order("created_at desc").each do |comment|%>
<% end %>
Share:
14,012
hyperrjas
Author by

hyperrjas

Code Lover Ror, Nodejs, React/Redux, Mongodb/Mysql/GraphQl

Updated on June 04, 2022

Comments

  • hyperrjas
    hyperrjas about 2 years

    I have a loop for with order_by for :created_at and :desc

    <% for comment in post.comments.order_by([:created_at, :desc]) %>
    <% end %>
    

    How can I doing the order_by([:created_at, :desc]) in block with each, e.j:

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

    Edited

    The code that working fine for me its:

    post.comments.order([:created_at, :desc])[0,5].each do |comment|
    

    with the [0,5] limit the result to interval.

  • hyperrjas
    hyperrjas over 12 years
    Thank you very much. For me working fine this: post.comments.order([:created_at, :desc])[0,5].each do |comment|