views:

25

answers:

3

I have read the following rails guide : http://guides.rails.info/active_record_querying.html

in there exemple a client has many orders and orders belong to clients.

They explain how to find a lot of stuff from client. But if i want all orders from yesterday, with the corresponding client name, how do i retrieve the client from an order?

A: 
today = Date.today
yesterday = today - 1.days
orders = Order.find(:all, :include => :client, :conditions => ["created_at >= :yesterday AND created_at <= :today", {:yesterday => yesterday, :today => today}])

You can now iterate orders and do order.client to retrieve the Client object. The :include => :client will make RoR automatically include the it in the query (rather than lazy loading).

Matt S
A: 

You can do something like this:

orders = Order.all(:conditions => ["DATE(created_at) = DATE(?)",
                   :include => :client,
                   Time.now - 1.day])
client = orders.first.client
John Topley
A: 
# controller
@orders = Order.all(:include => :client,
   :conditions => ["created_at = ?", Date.today-1])

# view
<% @orders.each do |order| %>
   <%= order.client.name %>
<% end %>

Edit:

If you have an specific order id, you can do your search like

@order = Order.first(id, :include => :client)

and access the client the same way

@order.client.name
j.
ok, i understand it better now. and if i have a specific order, i do :order(:include=>client, :conditions=> id=order.client_id)?
Sylario
you Should be able to do `Order.find(id, :include = :client)`
Matt S
@Sylario: edited my answer :]
j.