搜索

2012-08-09 54 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'變量?您應該先將查詢結果轉換爲散列或字符串數​​組。 – 2012-08-09 17:00:11

+0

這裏輸出我有,它看起來像方法firstname isnt'定義 – Jseb 2012-08-09 17:02:30

+0

那麼,你有2種類型的結果,客戶和事件。您可以檢查課程,例如'如果result.class ==客戶'。所以你想要在一個列表中混合客戶和事件? – 2012-08-09 17:08:34

回答

2

在我看來,一個更好的辦法是將每個類型的結果存儲在實例變量,而不是合併數據集。我這樣說是因爲我懷疑你的客戶和事件表是相同的。

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

在您的觀點中,您可以看到在客戶中找到的結果以及在事件中找到的結果。

1

在ruby方法中返回最後一條語句的值。我不知道你的意思是「結合」。如果哈希是好的:

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

關閉,但不輸出我期待的結果,我更新了我的帖子,以深入解釋我在找什麼 – Jseb 2012-08-09 16:43:43