在rails中搜索不同的Model Query

时间:2012-08-09 15:43:21

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

我有多个模型,我希望允许客户搜索客户表和事件表 这是我的模特

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

哪个返回事件查询,但我想返回它们,我该如何组合查询?

更新

这就是我想要做的,同时搜索多个模型,如客户和事件。

我在我的模型搜索中定义了def 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 %>

2 个答案:

答案 0 :(得分:2)

在我看来,更好的方法是将每种类型的结果存储在实例变量中,而不是组合数据集。我这样说是因为我怀疑你的客户和事件表是一样的。

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

在您的视图中,您可以显示在客户中找到的结果以及在事件中找到的结果。

答案 1 :(得分:1)

ruby方法中的

返回last语句的值。我不知道你的意思是“结合”。如果哈希是可以的:

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