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