검색

2012-08-09 3 views
2

잘 나는 여러 모델을하고 난 고객이 고객 테이블과 여기에 이벤트 테이블 내 모델검색

def self.search(search) 
    if search 
    Customer.find(:all, :conditions => ['first_name LIKE ?', "%#{search}%"]) 
    Event.find(:all, :conditions => ['title LIKE ?', "%#{search}%"]) 
    else 
    Customer.find(:all) 
    Event.find(:all) 
    end 
end 

반환 이벤트 쿼리를 검색 할 수 있도록하려면,하지만 난 둘 다 반환하려면 쿼리를 어떻게 결합합니까?

업데이트 : 여기

정확히 내가하고 싶은 것을, 같은 동시에 고객 및 이벤트와 같은 여러 모델에 대한 검색이 있습니다.

내가 데프 self.search 한 (검색) 내 모델 검색에서 정의하고 난 컨트롤러

class SearchesController < ApplicationController 
    def query 
    #@results = Search.new(params[:search][:query]).results 
    @results = Search.search(params[:query]) 
    end 

를하고 난 할 방법을 잘 내 모델에서 고객 및 이벤트를 볼 수 원하는

여기서보기가 옳은지 확실하지 않은 샘플보기

<h1>Search Results</h1> 
<% @results.each do |result| %> 
    <div> 
    <%= result.first_name %> 
    <% if admin? %> 
     <%= link_to 'Show', '#' %> 
     <%= link_to 'Edit', '#' %> 
     <%= link_to 'Destroy', '#' %> 
    <% end %> 
    </div> 

    <div> 
    <%= result.title %> 
    <% if admin? %> 
     <%= link_to 'Show', '#' %> 
     <%= link_to 'Edit', '#' %> 
     <%= link_to 'Destroy', '#' %> 
    <% end %> 
    </div> 
<% end %> 
+0

'+'연산자를 사용하여 두 개의 배열을 결합 할 수 있습니다. 그러나 다른 방법에 응답하는 결과 안에 다른 모델이있을 것입니다. '@ results' 변수를 어떻게 사용할 계획입니까? 아마도 쿼리 결과를 먼저 해시 또는 문자열 배열로 변환해야합니다. –

+0

여기에 출력이 있는데, 메서드 firstname isnt처럼 보입니다. '정의 – Jseb

+0

글쎄, 결과, 고객 및 이벤트의 두 가지 유형이 있습니다. 예를 들어 수업을 확인할 수 있습니다. 'if result.class == Customer'입니다. 따라서 고객과 이벤트를 하나의 목록에 혼합하고 싶습니까? –

답변

2

나에게 더 나은 방법은 인스턴스 변수에 각 유형의 결과를 저장하고 데이터 세트를 결합하지 않는 것입니다. 나는 당신의 고객과 사건 표가 동일하다는 것을 의심하기 때문에 이것을 말한다.

class SearchesController < ApplicationController 
    def query 
    @customers = Customer.where('first_name LIKE ?', params[:query]) 
    @events = Event.where('title LIKE ?', params[:query]) 
    end 

보기에서 고객의 결과와 이벤트의 결과를 표시 할 수 있습니다.

1

루비 메서드는 마지막 문의 값을 반환합니다. 나는 당신이 "결합하다"라는 말을 모른다. 해시가 괜찮 으면 :

def self.search(search) 
    if search 
    {customers: Customer.find(:all, :conditions => ['first_name LIKE ?', "%#{search}%"]), 
    events: Event.find(:all, :conditions => ['title LIKE ?', "%#{search}%"])} 
    else 
    {customers: Customer.find(:all), 
    events: Event.find(:all)} 
    end 
end 
+0

Closes, 그러나 결과를 출력하지 않는다. 찾고있는 바가 더 깊다. – Jseb