I have 3 models: Carriers, Products, Rates. Each Carrier has_many :products and each Product has_many :rates. I am trying to create an html table that will loop through each product and display only the most current rate. I assume I need to store this in an array (or hash?), but not quite sure how (as I am new to programming, but learning!). Can someone please help?
Add a comment
|
2 Answers
The most recent rate is the last rate created on your database. And if this information is true, that means a SQL query getting just one (limit 1) row ordered by the creation date descending (created_at DESC) would get the record you want. Knowing this you can create a scope in your rate model:
scope :current_rate, order('rates.created_at DESC').limit(1).first
# As @AntohnyAlberto said, limit would bring an array, so you may use .first on the results
# Or you can use just .first, as it would bring only the first one
scope :current_rate, order('rates.created_at DESC').first
And use this scope on your product loop in your view:
<%= product.rate.current_rate %>
1 Comment
Anthony Alberto
Using
limit, AR will bring back a collection of models ... better use first instead to get an object back directly : scope :current_rate, order('rates.created_at DESC').first