Ruby ActiveRecord has_one有条件

时间:2011-08-11 11:02:04

标签: sql ruby-on-rails ruby activerecord

假设我有一些Item可供出售,而且我在历史上跟踪他们的Cost

class Cost < ActiveRecord::Base
  belongs_to :item

  # eg: costs.amount = 123.45; costs.item_id = 1; costs.created_at = 2011-08-11 16:28
end

class Item < ActiveRecord::Base
  has_many :costs

  # eg: items.id = 1; items.name = Cheese Sandwich
end

此代码有效,我可以提取我正在销售的商品的所有先前费用。

我觉得应该可以为Item设置第二个条款,以便我可以直接提取当前价格:

class Item < ActiveRecord::Base
  has_many :costs
  has_one :current_cost, :class_name => :costs, :conditions => 'MAX(created_at)'
end

my_item.current_cost # => <£123.45, 45 minutes ago>

任何想法如何实现这一目标?

3 个答案:

答案 0 :(得分:4)

class Item < ActiveRecord::Base
  has_many :costs
  def current_cost
    self.costs.order("created_at DESC").first
  end
end

my_item.current_cost

答案 1 :(得分:2)

has_one :current_cost, :class_name => :costs, :order => 'create_at DESC'

答案 2 :(得分:0)

您可以使用范围:

class Item < ActiveRecord::Base
  has_many :costs
  scope :current_cost, limit(1).order("created_at DESC")
end

用法:

my_item.current_cost