title: Rails Search Across Multiple Models
body: <p>I have an issue. I have a show view that acts as a dashboard and brings in records from other models and then models associated to that. I have a simple search form that is working fine to search through one model, but I don't know how to have it look through its associated models as well. I don't think a full text search is necessary and I am not sure how it would work because I don't want something that is going to search across the whole site. </p>
  
  <p>Thanks</p>
  
  <p>companies/show/1</p>
  
  <pre><code>&lt;div id="form"&gt;
    &lt;div class="search"&gt;
     &lt;% form_tag battalion_company_path, :method =&gt; :get do %&gt;
     &lt;p&gt;
     &lt;%= text_field_tag :search, params[:search] %&gt;
  
     &lt;%= submit_tag "Search", :name =&gt; nil %&gt;
  
     &lt;/p&gt;
   &lt;% end %&gt;
  &lt;/div&gt;
  &lt;/div&gt;
  
  &lt;div id="bc_box"&gt;
  &lt;% @soldiers.each do |soldier| %&gt;
  &lt;div id="bc_focus"&gt;
     &lt;div class="right"&gt;
      &lt;%= link_to image_tag("../images/buttons/info.png", :border=&gt;0),  battalion_company_soldier_path(@battalion, @company,soldier) %&gt;
      &lt;%= link_to image_tag("../images/buttons/edit.png", :border=&gt;0), edit_battalion_company_soldier_path(@battalion, @company,soldier) %&gt;
      &lt;/div&gt;
     &lt;%=h soldier.rank %&gt; &lt;%=h soldier.lastname %&gt;&lt;br /&gt;
     Cell: &lt;%=h soldier.cellphone %&gt;&lt;br /&gt;
     &lt;% soldier.primaries.each do |primary| %&gt;
     &lt;p&gt;
     &lt;%=h primary.firstname %&gt; &lt;%=h primary.lastname %&gt; (&lt;%=h primary.relationship %&gt;)&lt;br /&gt;
  
     (c):&lt;%=h primary.cellphone %&gt;&lt;br /&gt;
     &lt;%=h primary.email %&gt;&lt;br /&gt;
     &lt;/p&gt;
      &lt;% end %&gt;
  
  &lt;/div&gt;
    &lt;% end %&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>soldier.rb</p>
  
  <pre><code>def self.search(search)
    if search
      find(:all, :conditions =&gt; ['email LIKE ? OR lastname LIKE ? OR firstname LIKE ?', "%#{search}%", "%#{search}%", "%#{search}%"])
    else
      find(:all, :order =&gt; 'lastname')
    end
  end
  </code></pre>
  
  <p>companies_controller</p>
  
  <pre><code>@soldiers = @company.soldiers.search(params[:search])
  @primary = @company.primaries.find(:all,:conditions =&gt; ["relationship = 'Spouse'"])
  </code></pre>