I have 2 models: Microposts (which has_many :comments) and Comments (which belongs_to :micropost).
In the following view:
views/micropost/index.html.erb:
<h2>Micropost Index</h2>
<% @microposts.each do |micropost| %>
<h2><%= micropost.title %></h2>
<p><%= micropost.content %></p>
<p><%= micropost.comments.count %></p>
<ul>
<li><%= link_to 'Show', micropost %></li>
<li><%= link_to 'Edit', edit_micropost_path(micropost) %></li>
<li><%= link_to 'Destroy', micropost, confirm: 'Are you sure?', method: :delete %></li>
</ul>
<br />
<% end %>
controller/microposts.rb:
def index
@microposts = Micropost.all
end
I was able to get the number of comments for each micropost:
<p><%= micropost.comments.count %></p>
How can I sort microposts by number of comments?
Any suggestions to accomplish this?
You can create a method in
micropost.rband sort by it like a virtual attribute:Then sort your collection with
sort_bymethod:Also, you can use
reversemethod if you need an opposite sort direction.