2010-05-27 2 views
0

다음 레일 가이드를 읽었습니다. 예를 들어 고객이 많은 주문과 주문을 클라이언트에 가지고있는 경우에 http://guides.rails.info/active_record_querying.htmlAssociation : client.order, ok하지만 주문에서 클라이언트를 어떻게 검색합니까?

등이 있습니다.

그들은 클라이언트에서 많은 것을 찾아내는 방법을 설명합니다. 그러나 어제의 모든 주문을 해당 고객 이름과 함께 원하면 주문에서 클라이언트를 어떻게 검색합니까?

답변

0
# controller 
@orders = Order.all(:include => :client, 
    :conditions => ["created_at = ?", Date.today-1]) 

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

편집 : 당신이 특정 순서 id이있는 경우

, 당신처럼 검색을 할 수

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

동일한 방법으로 클라이언트에 액세스하십시오.

@order.client.name 
+0

좋습니다. 이제는 더 잘 이해합니다. 특정 주문이있는 경우 다음을 수행합니다. 주문 (: include => client, : conditions => id = order.client_id) ? – Syl

+0

당신은'Order.find (id, : include = : client)' –

+0

@ Sylario : edit my answer :] 할 수 있어야합니다. –

0
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}]) 

이제 orders를 반복하고 클라이언트 개체를 검색 order.client 할 수 있습니다. :include => :client은 RoR이 자동으로 쿼리에 포함되도록합니다 (지연로드가 아닌).

0

당신이 뭔가를 할 수 있습니다

orders = Order.all(:conditions => ["DATE(created_at) = DATE(?)", 
        :include => :client, 
        Time.now - 1.day]) 
client = orders.first.client 
관련 문제