首页 > 解决方案 > 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?

标签: ruby-on-railsrubymethodsviewmodel

解决方案


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.


推荐阅读