× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Ruby on Rails - how would I change the order of posts displayed to newest at the top of page?

Simone Carletti
Mar 21, 2015
<p>Add the <code>order</code> to the query.</p> <pre><code>@houses = House.page(params[:page]).per(20).order(created_at: :desc) </code></pre> <p>Even better, you should avoid to chain multiple scopes directly in the controller. This approach is very hard to test. Create a custom method.</p> <pre><code>class House &lt; ActiveRecord::Base # ... def self.listing(page) order(created_at: :desc).page(params[:page]).per(20) end end </code></pre> <p>and call it in your controller</p> <pre><code>@houses = House.listing(params[:page]) </code></pre> <p>In this way, you can test both <code>listing</code> and the controller separately with unit tests.</p> <p>As a side note, even if you are a beginner, you should not skip the good habit of reading a basic book before writing code, and the official documentation. ;)</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/28320826/Ruby%20on%20Rails%20-%20how%20would%20I%20change%20the%20order%20of%20posts%20displayed%20to%20newest%20at%20the%20top%20of%20page?/28320864">Stack Overflow</a>.</p>
comments powered by Disqus