jonty
jonty

Reputation: 470

Best data structure and design for this feature

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

Upvotes: 3

Views: 155

Answers (2)

srboisvert
srboisvert

Reputation: 12749

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.

Upvotes: 3

Sam Coles
Sam Coles

Reputation: 4043

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>

Upvotes: 1

Related Questions