jordan.baucke
jordan.baucke

Reputation: 4328

Rails :include specific records from association

I'm trying to get a few records from a has_many association in my model.

I have a model that has_many association to a set of records that are sort of a history of transactions that record some data about the parent at the time of another transaction.

class Character < ActiveRecord::Base
    has_many :character_histories
end

class CharacterHistory < ActiveRecord::base
    belongs_to :character
end

It's easy to get all 'CharacterHistory' records, but I only want to include the first record that was created 12,24hours ago, etc. so I can look at the last transaction that took place at that time frame.

As an added bonus, I'd also like to be-able to get the max for a column on ALL records that are returned for the association...

Update w/ Solution

I added a 'Scoped Module' to my model.

class CharacterHistory < ActiveRecord::Base
  module Scopes
    def last
      order("created_at DESC").first
    end

    def first_less_than_12_hours_ago
      where("created_at <= '#{12.hours.ago}'").order("created_at DESC").first
    end

    def first_less_than_24_hours_ago
      where("created_at <= '#{24.hours.ago}'").order("created_at DESC").first  
    end

    def all_time_high
      maximum(:value)
    end
  end
  extend Scopes

end

This was inspired from the solution I got here, and from this article: http://www.railway.at/2010/03/09/named-scopes-are-dead/

Upvotes: 0

Views: 369

Answers (1)

Pawel
Pawel

Reputation: 944

You could create scopes in character_histories for every credentials you need, something like this:

scope :first_less_than_12_hours_ago, lambda {where("date >= '#{12.hours.ago}'").order("date DESC").first}

scope :unknown_column_max, maximum(:unknown_column)

and then:

character.character_histories.first_less_than_12_hours_ago
character.character_histories.unknown_column_max

Upvotes: 1

Related Questions