ruby-on-rails - Report only first event of of model for each item - Rails model/view
问题描述
I'm working on a problem when the a product has_many product_selections. I'm trying to report the history of the product - one aspect of which includes getting the first time each product in my array was selected in order to determine how long said product has been in circulation.
In my product_selection model:
belongs_to :product
def time_since_first_use
(Time.now - self[0].staged_at)
end
# staged_at is a datetime attribute
The product model then picks this up:
def tag_time_since_first_use
self.product_selections.time_since_first_use
end
And I try to render it in the view (general formatting is simplified):
<% @products.order(created_at: :desc).each do |product| %>
<%= humanize_seconds(product.tag_time_since_first_use)%>
<%end%>
I had the [0] selection on the product model initially, and it rendered a repeated value for every item in the product list. How do I fix this?
解决方案
class Product
def tag_time_since_first_use
Time.now - product_selections.order(staged_at: :asc).first.staged_at
end
end
If you're using the tag_time_since_first_use
frequently, it will be better to save the value in a staged_at
attribute on the product, when the first product_selection
is created for the product to avoid querying each time.
推荐阅读
- javascript - 保存到 MongoDb 时的节点 UnhandledPromiseRejectionWarning
- python-3.x - 如何逐个文件夹实现批处理
- c# - 没有足够的配额可用于在 UpdateWindowSettings 上处理此命令
- html - 将 div 排成一行的问题
- docker - 连接到 docker 上运行的 grpc 服务器时出现 DNS 解析失败错误
- python - Python - Ply Parser:如何在任何我想要的地方停止解析?
- c# - httpget请求webapi core 3.0的流利验证
- python - 在终端模式下执行时,它工作正常,但如果我从文件中执行相同的代码,例如 xyz.py
- python - 将特定时期的概率数据框转换为 n 个时期内至少一次的概率?
- android - MYSQL 随机选择候选行但只选择一次