Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1

Search in different Model Query in rails


Well i have multiple model and i want to allow the customer to search on a customer table and an event table Here my model

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

Which return event query, but i want to return both of them, how do i combine the query?

Update:

Here exactly what I want to do, there is a search for multiple model such as customer and events at the same time.

I have def self.search(search) define in my model search and i have a controller

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

and i want to view customer and event in my models not sure how to do that

Here a view sample not sure if its right or wrong

<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 %>

Solution

  • Seems to me a better way is to store each type of result in instance variables and not combine the data sets. I say this because I doubt your customer and event tables are identical.

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

    In your view you could display results found in Customers and results found in Events.