为每个项目只报告模型的第一个事件-Rails模型/视图



当一个产品有_many product_selections时,我正在处理一个问题。我试图报告该产品的历史,其中一个方面包括第一次选择我的阵列中的每种产品,以确定该产品的流通时间。

在我的产品选择模型中:

belongs_to :product
def time_since_first_use
(Time.now - self[0].staged_at)
end 
# staged_at is a datetime attribute

然后产品模型会发现:

def tag_time_since_first_use
self.product_selections.time_since_first_use
end 

我试着在视图中呈现它(通用格式被简化(:

<% @products.order(created_at: :desc).each do |product| %>
<%= humanize_seconds(product.tag_time_since_first_use)%>
<%end%>

我最初对产品模型进行了[0]选择,它为产品列表中的每个项目提供了一个重复值。我该如何解决这个问题?

class Product
def tag_time_since_first_use
Time.now - product_selections.order(staged_at: :asc).first.staged_at
end
end

如果您经常使用tag_time_since_first_use,最好在为产品创建第一个product_selection时将值保存在产品的staged_at属性中,以避免每次都进行查询。

最新更新