Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm creating a simple house listing page to get to grips with Rails and I currently have an add post page set up which posts to the index page however the newest post is displaying at the bottom of the page. How could I reverse the order of my posts to display newest posts at the top?

Not sure which code snippets I should provide but below is my code:

houses_controller.rb -

class HousesController < ApplicationController
  def index
    @houses = House.page(params[:page]).per(20)
  end

  def new
    @house = House.new
  end

  def create
    @house = House.new(params.require(:house).permit(:title, :price, :description, :image))
  if @house.save
    redirect_to root_path
  else
    render "new"
  end
  end

end

index.html.erb -

<% @houses.each do |house| %>

  <div class="house">
    <p><%= house.image %></p>
    <h2><%= house.title %></h2>
    <h2><%= house.price %></h2>
    <p><%= house.description %></p>
  </div>
<% end %>

<p><%= paginate @houses %></p>

house.rb -

class House < ActiveRecord::Base
    validates :title, presence: true
    validates :price, presence: true
    validates :description, presence: true
    validates :image, presence: true
end
like image 729
user2498890 Avatar asked Feb 11 '23 00:02

user2498890


1 Answers

Add the order to the query.

@houses = House.page(params[:page]).per(20).order(created_at: :desc)

Even better, you should avoid to chain multiple scopes directly in the controller. This approach is very hard to test. Create a custom method.

class House < ActiveRecord::Base
  # ...

  def self.listing(page)
    order(created_at: :desc).page(params[:page]).per(20)
  end
end

and call it in your controller

@houses = House.listing(params[:page])

In this way, you can test both listing and the controller separately with unit tests.

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. ;)

like image 199
Simone Carletti Avatar answered Feb 14 '23 00:02

Simone Carletti