![](/img/trans.png)
[英]ActiveRecord: Join for number of subobjects of has_one relationship
[英]Ruby ActiveRecord has_one with conditions
假设我有一些待售的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>
任何想法如何实现这一目标?
class Item < ActiveRecord::Base
has_many :costs
def current_cost
self.costs.order("created_at DESC").first
end
end
my_item.current_cost
has_one :current_cost, :class_name => :costs, :order => 'create_at DESC'
您可以使用 scope:
class Item < ActiveRecord::Base
has_many :costs
scope :current_cost, limit(1).order("created_at DESC")
end
用法:
my_item.current_cost
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.