Class Item
has_many :prices
has_one :current_price
end
Class Price
belongs_to :item
#date the price was set attribute
#price attribute
end如何在"current_price“字段中找到所有im销售的项目,包括(急切地加载)当前价格(持有给定项目的最大日期的价格)?
例如:
表项:
id=1 _ name="the_hobbit“
表价:
id=1 _~_( item_id=1 )_
id=2 _( item_id=1 )_
id=3 _
@item = Items.find(1)
@item.current_price # should print "19.99$"编辑:我相信我的问题叫做"greatest-n-per-group“,但我想不出如何通过一个"has_one”关联来正确地解决这个问题。
发布于 2013-01-18 06:05:38
在has_one宏上使用order选项:
class Item
has_many :prices
has_one :current_price, :order => "date DESC"
end当然,Has_one在sql级别上只包含一个价格。但是,如果您已经用has_many :prices加载了每个项目的所有价格,那么您可以使用一些可枚举的优点来使用纯Ruby。
@item.prices.sort_by(&:date).last ...which会给你最新的价格。
我在做的时候你最好这么做:
class Item
has_many :prices, :order => "date"
has_one :current_price, :order => "date DESC"
end
@item.prices.last 因为价格是按SQL预先排序的(这样更快.)
发布于 2013-01-18 08:36:38
没有其他关联的必要,只需使用自定义方法即可。
Class Item
has_many :prices
def current_price
return self.prices.last
end
end发布于 2017-02-13 10:47:24
您应该为此使用class_name和外键,还需要按日期或所需的排序,在我的例子中是版本,对于您的情况,我编写了created_at字段。
class Item
has_one :current_price, -> { order created_at: :desc }, class_name: 'Price', foreign_key: :item_id
end现在,当你需要最新的价格时,你只需要打电话。
@item = Item.find_by(id: params:id).current_price
它返回给您该项目的最新价格,您还可以将该价格与项目哈希合并。
@item = Item.find_by(id: params:id) @item.merge({current_price:@item.current_price})
输出将使用关键的:current_price和最新相关价格的值进行散列。
https://stackoverflow.com/questions/14393165
复制相似问题