2011-08-11 44 views
0

比方說,我有一些Item S表示銷售,而我跟蹤他們Cost的歷史:紅寶石的ActiveRecord HAS_ONE與條件

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> 

任何想法如何實現這一目標?

回答

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

my_item.current_cost 
0

您可以使用範圍:

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

用法:

my_item.current_cost 
+0

範圍都死了:) – fl00r

+0

這不會像'has_one'..'my_item工作。 current_cost'仍然會給出一個活動的記錄關係(就像一個數組),並且必須調用'my_item.current_cost.first'來獲取記錄。 – rubyprince

+0

你說得對,需要使用:my_item.current_cost.first,但通過範圍,你可以輕鬆地添加更多條件 – Sector

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