Association : client.order , ok but how do you retrieve the client from the order?
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 explai开发者_开发问答n 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?
# 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
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).
You can do something like this:
orders = Order.all(:conditions => ["DATE(created_at) = DATE(?)",
:include => :client,
Time.now - 1.day])
client = orders.first.client
精彩评论