0

Railscast #223

At 6:30 in this RailsCast it mentions real data is going to be used instead of arbitrary data.

The line in the /app/views/orders/index.html.erb file

data: [1, 2, 5, 7, 3]

is replaced with

data: <%= (3.weeks.ago.to_date..Date.today).map { |date| Order.total_on(date).to_f}.inspect %>  }]

At 7:30 he then create a class method in the order model.

/app/models/order.rb

class Order < ActiveRecord::Base
  def self.total_on(date)
    where("date(purchased_at) = ?",date).sum(:total_price)
  end
end

I don't understand how this fetches the real data. How is it taken from the database? He refers to the orders table numerous times but I don’t see where where the connection is made.

Thanks for reading.

LogiKal
  • 49
  • 3
  • 12

1 Answers1

1

In the view code, he maps the last three weeks worth of dates to the result of

Order.total_on(date)

The method Order::total_on calls where, which is an ActiveRecord query method that adds conditions to the query (see http://guides.rubyonrails.org/active_record_querying.html#conditions).

Since in the context of the Order::total_on method, self refers to the Order class, what we're actually doing here is the query:

Order.where("date(purchased_at) = ?", date)

Now that actually returns an ActiveRecord::Relation object that allows you to chain more query methods on it before executing the query. We then call #sum on that relation (http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-sum) to further convert the query. The generated SQL would look something like:

SELECT SUM(orders.total_price) AS sum_id FROM orders WHERE (date(purchased_at) = #{date});

It's a bit hard to guess what the specific point of confusion here is, so if that's still unclear please comment.

(Edit in case I'm assuming too much: The actual connection between the Order class and the orders table in the database is made with the very first line of app/models/order.rb, where the class inherits from ActiveRecord::Base. ActiveRecord does a lot of magic--see http://api.rubyonrails.org/files/activerecord/README_rdoc.html for a basic introduction.)

gregates
  • 6,607
  • 1
  • 31
  • 31
  • Thanks for the guidance. It was the behind the scene work by ActiveRecord that was missing in understanding the whole picture. – LogiKal Jul 08 '13 at 23:55