2012-08-12 55 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

相关问题