0

我正在尝试从has_many我的模型中的关联中获取一些记录。

我有一个模型,该模型has_many与一组记录相关联,这些记录是一种交易历史,在另一笔交易时记录有关父母的一些数据。

class Character < ActiveRecord::Base
    has_many :character_histories
end

class CharacterHistory < ActiveRecord::base
    belongs_to :character
end

获取所有“CharacterHistory”记录很容易,但我只想包括在 12.24 小时前创建的第一条记录,等等,这样我就可以查看在那个时间范围内发生的最后一笔交易。

作为额外的奖励,我还希望能够获得为关联返回的所有记录的列的最大值......

更新/解决方案

我在我的模型中添加了一个“范围模块”。

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/

4

1 回答 1

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
于 2012-08-12T21:25:44.410 回答