2012-08-12 54 views
0

我試圖從我的模型中的has_many關聯中獲取幾條記錄。Rails:包含來自關聯的特定記錄

我有一個模型,has_many關聯到一組記錄,這些記錄是在另一個事務時記錄有關父項的一些數據的事務歷史記錄。

class Character < ActiveRecord::Base 
    has_many :character_histories 
end 

class CharacterHistory < ActiveRecord::base 
    belongs_to :character 
end 

可以很容易地得到所有「CharacterHistory」的記錄,但我只希望包括創建12,24hours前,第一個記錄等,所以我可以看看那個發生在當時的最後一筆交易幀。

作爲額外的獎勵,我也想成爲,能夠得到最大的一列進行ALL記錄了爲關聯返回...

更新瓦特/解決方案

我在模型中添加了一個'Scoped模塊'。

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 

這是從我來到這裏的解決方案的啓發,從這篇文章:http://www.railway.at/2010/03/09/named-scopes-are-dead/

回答

1

你可以爲每一個你需要的憑據創建character_histories範圍,這樣的事情:

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

scope :unknown_column_max, maximum(:unknown_column) 

然後:

character.character_histories.first_less_than_12_hours_ago 
character.character_histories.unknown_column_max 
+0

我最終走了一個不同的方向,但它仍然工作編輯(你讓我在正確的軌道與範圍)。我更新了原始問題以顯示我所做的。 – 2012-08-13 01:42:15

相關問題