Search code examples
ruby-on-railsrails-activerecordruby-on-rails-2

What's the Rails way to access the previous record in a series?


Say I have a Statement model, which has_many :months. There are always 12 months associated with a statement, but the first month can vary (eg months = [Mar, Apr, May...Jan, Feb])

Given a certain month, what's the MVC way to find the previous month?

I find myself accessing it through the statement which feels dirty:

# statement.rb
has_many :months

def previous_month(month)
  if months.index(month) == 0
    return nil
  else
    return months[months.index(month) - 1]
  end
end

# blergh
prev_month = month.statement.previous_month(month)

Should I have a previous_month_id column in my database? How would you implement this functionality? I'm using Rails 2.3.x.


Solution

  • I would define it on the Month model to cut back on the roundtrips.

    # month.rb
    class Month < ActiveRecord::Base
      belongs_to :statement, :include => :months
    
      def previous
        return nil if self.index == 0
        find_or_create_by_index_and_statement_id(self.index - 1, self.statement.id)
      end
    
      def index
        statement.months.index self
      end
    end
    

    so that you can get june.previous. This should even work on unsaved records.