开发者

Rails Search Across Multiple Models

开发者 https://www.devze.com 2022-12-16 14:59 出处:网络
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 thro

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'"])


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消