我遇到了一个问题,在我的 Rails 应用程序中,我在搜索中得到重复的结果,该应用程序允许用户在数据库中搜索项目。
这是项目模型中的搜索功能:
def self.search(search_industry, search_role, search_techs_ids)
_projects = Project.scoped
if search_industry.present?
_projects = _projects.where ['industry LIKE ?', like(search_industry)]
end
if search_role.present?
_projects = _projects.where ['role LIKE ?', like(search_role)]
end
if search_techs_ids.present?
_projects = _projects.includes(:technols).where("technols.id" => search_techs_ids)
end
_projects
end
这是我的搜索页面的一部分
<div class="tech">
<%= fields_for(@project_technol) do |ab| %>
Technologies :
<% tech_ids = params[:technols][:id].reject(&:blank?) unless params[:technols].nil? %>
<%if params[:technols].nil?%>
<%= collection_select(:technols, :id, @all_technols, :id, :tech, {}, {:multiple => true} ) %>
<% else %>
<%= collection_select(:technols, :id, @all_technols, :id, :tech, {}, {:multiple => true, :selected => tech_ids } ) %>
<% end %>
</div>
这是我的搜索操作:
def search
tech_ids = params[:technols][:id].reject(&:blank?) unless params[:technols].nil?
@search = params[:industry], params[:role], tech_ids
@project_search = Project.search(*@search).order(sort_column + ' ' + sort_direction).paginated_for_index(per_page, page)
@search_performed = !@search.reject! { |c| c.blank? }.empty?
@project = Project.new(params[:project])
@all_technols = Technol.all
@project_technol = @project.projecttechnols.build
respond_to do |format|
format.html # search.html.erb
format.json { render :json => @project }
end
end
该问题现在已排序,但在修复该问题时,我注意到当我搜索一项技术时,表格中会显示正确的项目,但在技术列中,它旨在显示属于该项目的所有技术,但它只显示我搜索的那个:
<% @project_search.each do |t| %>
<tr>
<td><ul>
<% t.technols.each do |technol| %>
<li><%= technol.tech %><!/li>
<% end %>
</ul></td>
有任何想法吗?在我的模型中,我曾经有这段代码可以正确显示表格,但显示重复的结果。
if search_techs_ids.present?
_projects = _projects.joins(:technols).where("technols.id" => search_techs_ids)
end
任何帮助都将不胜感激。提前致谢
解决方案见下面的答案
@shioyama 和 @tommasop 都帮助解决了这个问题。
解决方案是更改列所在的搜索视图
<td><ul>
<% t.technols(force_reload=true).each do |technol| %>
<li><%= technol.tech %></li>
<% end %>
</ul></td>