Rails Search Across Multiple Models

自作多情 提交于 2019-12-30 04:35:11

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/2044415/rails-search-across-multiple-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!