0

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?

2 Answers 2

1

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 %>
Sign up to request clarification or add additional context in comments.

1 Comment

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
0

I would do the model like this:

class Product < ActiveRecord::Base
  def current_rate
    rates.order('created_at ASC').last
  end
end

And then this in the view:

<%= product.current_rate %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.