views:

101

answers:

2

In my Rails app, I have a section called Situations, which is basically a textual description of a situation. But there are several of them. I want to be able to display only one at a time and each one on its own page (the newest created ones first), and then at the bottom of the page I have links that go to Older and Newer situations.

Assume that I have a @situations object in my code that contains all the situations that I want to display. What should I do next (in the controller and the view).

+1  A: 

models/situation.rb

class Situation < ActiveRecord::Base
  default_scope :order => 'created_at desc'
end

controllers/situations_controller.rb

class SituationsController < ActionController::Base
  def index
    @situations = Situation.all
  end
end

views/situations/index.html.erb

<h1>Situations</h1>
<%= render @situations %>

views/situations/_situation.html.erb

<h2><%= situation.name -%></h2>
<p><%= situation.description -%></p>
Sam C
What about the links at the bottom? One situation per page.
jonty
+3  A: 

I'd use pagination (will_paginate) and set the number of items per page to 1.

Then you can use current_page and next_page to make your links. See source here.

Other that it would just be a standard index action with the changes made required for will_paginate.

This screencast should give you a good idea what you need but be aware that there have been some changes to the plugin since it was made. Details are on the will_paginate github wiki.

srboisvert
Here: http://gitrdoc.com/rdoc/mislav/will_paginate/8888651be8d6656bdf2378731d91a8badbaa2556/classes/WillPaginate/ViewHelpers.html#M000131 on the bottom is information how to do exactly what you want.
klew
Nice. How did you find that rdoc?
srboisvert