Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Search Across Multiple Models

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.

Thanks

companies/show/1

<div id="form">
  <div class="search">
   <% form_tag battalion_company_path, :method => :get do %>
   <p>
   <%= text_field_tag :search, params[:search] %>

   <%= submit_tag "Search", :name => nil %>

   </p>
 <% end %>
</div>
</div>

<div id="bc_box">
<% @soldiers.each do |soldier| %>
<div id="bc_focus">
   <div class="right">
    <%= link_to image_tag("../images/buttons/info.png", :border=>0),  battalion_company_soldier_path(@battalion, @company,soldier) %>
    <%= link_to image_tag("../images/buttons/edit.png", :border=>0), edit_battalion_company_soldier_path(@battalion, @company,soldier) %>
    </div>
   <%=h soldier.rank %> <%=h soldier.lastname %><br />
   Cell: <%=h soldier.cellphone %><br />
   <% soldier.primaries.each do |primary| %>
   <p>
   <%=h primary.firstname %> <%=h primary.lastname %> (<%=h primary.relationship %>)<br />

   (c):<%=h primary.cellphone %><br />
   <%=h primary.email %><br />
   </p>
    <% end %>

</div>
  <% end %>
</div>

soldier.rb

def self.search(search)
  if search
    find(:all, :conditions => ['email LIKE ? OR lastname LIKE ? OR firstname LIKE ?', "%#{search}%", "%#{search}%", "%#{search}%"])
  else
    find(:all, :order => 'lastname')
  end
end

companies_controller

@soldiers = @company.soldiers.search(params[:search])
@primary = @company.primaries.find(:all,:conditions => ["relationship = 'Spouse'"])
like image 472
looloobs Avatar asked Jan 11 '10 19:01

looloobs


1 Answers

How about a search engine behind your app such as Thinking Sphinx ? Leave the hard work of caching and searching to someone else and let your Rails app serve the result.

like image 147
Reuben Mallaby Avatar answered Oct 22 '22 14:10

Reuben Mallaby