Ruby on Rails:高级搜索 [英] Ruby on Rails: Advanced search

查看:45
本文介绍了Ruby on Rails:高级搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解制作高级搜索表单的最佳方式.我在互联网上进行了很好的搜索,寻找了一些方法,但我无法让它们工作,因为大多数建议已经过时.我已经问过一个问题,但我认为我太具体了,我无法解决我的问题.我想用一个搜索按钮搜索不同的文本框和下拉框.

编辑 2:

projects_controller:

def 索引@projects = Project.allresponse_to do |格式|format.html # index.html.erbformat.json { 渲染:json =>@项目}结尾结尾定义搜索@project_search = Project.search(params[:search]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 2, :page => params[:page])结尾# 获取/项目/1# 获取/projects/1.json高清秀@project = Project.find(params[:id])response_to do |格式|format.html # show.html.erbformat.json { 渲染 json: @project }结尾结尾# 获取/项目/新# 获取/projects/new.json定义新@project = Project.newresponse_to do |格式|format.html # new.html.erbformat.json { 渲染 json: @project }结尾结尾# 获取/projects/1/edit定义编辑@project = Project.find(params[:id])结尾# 发布/项目# POST/projects.json定义创建@project = Project.new(params[:project])@project.client = params[:new_client] 除非 params[:new_client].blank?@project.exception_pm = params[:new_exception_pm] 除非 params[:new_exception_pm].blank?@project.project_owner = params[:new_project_owner] 除非 params[:new_project_owner].blank?@project.role = params[:new_role] 除非 params[:new_role].blank?@project.industry = params[:new_industry] 除非 params[:new_industry].blank?@project.business_div = params[:new_business_div] 除非 params[:new_business_div].blank?response_to do |格式|如果@project.saveformat.html { redirect_to @project,注意:'项目已成功创建.'}format.json { 渲染 json: @project, status: :created, location: @project }别的format.html { 渲染动作:新"}format.json { 渲染 json: @project.errors, 状态: :unprocessable_entity }结尾结尾结尾# 放置/projects/1# PUT/projects/1.json定义更新@project = Project.find(params[:id])response_to do |格式|如果@project.update_attributes(params[:project])format.html { redirect_to @project,注意:'项目已成功更新.'}format.json { 头:no_content }别的format.html { 渲染动作:编辑"}format.json { 渲染 json: @project.errors, 状态: :unprocessable_entity }结尾结尾结尾# 删除/projects/1# 删除/projects/1.json销毁@project = Project.find(params[:id])@project.destroyresponse_to do |格式|format.html { redirect_to projects_url }format.json { 头:no_content }结尾结尾私人的helper_method :sort_column, :sort_direction定义排序列Project.column_names.include?(params[:sort]) ?参数[:排序]:项目名称"结尾定义排序方向%w[asc desc].include?(params[:direction]) ?参数[:direction] : "asc"结尾结尾

搜索视图:

搜索

<%= form_tag search_path, method: :get do %><%= hidden_​​field_tag :direction, params[:direction] %><%= hidden_​​field_tag :sort, params[:sort] %><%= text_field_tag :project_name, params[:project_name] %><%= text_field_tag :client, params[:client] %><%= submit_tag "搜索",名称:nil %><%结束%><表类=漂亮"><表格边框="1"><tr><th><%= sortable "project_name", "Project name" %></th><th><%=可排序的客户",客户"%></th><th>异常pm</th><th>项目所有者</th><th>Tech</th><th>角色</th><th>工业</th><th>金融</th><th>业务部门</th><th>状态</th><th>开始日期</th><第>结束日期<% if false %>进入日期</th><th>编辑日期</th><th>总结</th><th>经验教训</tStackh><th>客户利益</th><th>关键字</th><!th></th><!th></th><!th></th><%结束%></tr><% @project_search.each 做 |t|%><tr><td><%= t.project_name %></td><td><%=t.client%></td><td><%=t.exception_pm%<</td><td><%= t.project_owner %></td><td><%=t.tech%></td><td><%=t.role%</td><td><%= t.industry %</td><td><%=t.financials %</td><td><%=t.business_div %></td><td><%=t.status%</td><td><%= t.start_date %></td><td><%=t.end_date%></td><% if false %><td><%= t.entry_date %></td><td><%=t.edited_date %></td><td><%=t.summary%></td><td><%=t.lessons_learned%></td><td><%=t.customer_benefits%></td><td><%=t.keywords%></td><%结束%><!td><%#= link_to 'Show', project %></td><!td><%#= link_to 'Edit', edit_project_path(project) %></td><!td><%#= link_to 'Destroy', project, method: :delete, data: { confirm: 'Are you sure?'}%></td></tr><%结束%><br/><%= will_paginate (@project_search) %><%= button_to "再次搜索?", search_path, :method =>得到"%><%#结束%><%= button_to "Home", projects_path, :method =>得到"%>

项目.rb

class 项目 <ActiveRecord::Baseattr_accessible :business_div, :client, :customer_benifits, :edited_date, :end_date, :entry_date, :exception_pm, :financials, :industry, :keywords, :lessons_learned, :project_name, :project_owner, :date, : :总结,:技术validates_presence_of :business_div, :client, :customer_benifits, :end_date, :exception_pm, :financials, :industry, :keywords, :lessons_learned, :project_name, :project_owner, :role, :start_date, :status, :techdef self.search search_term返回范围除非search_term.present?where find(:all, :conditions => ['project_name OR client LIKE ?', "%#{search_term}%"])结尾结尾

路线:

FinalApp::Application.routes.draw 做资源:项目匹配搜索"=>"projects#search", :as =>:搜索根:到 =>'项目#index'结尾

如您所见,我离完成申请还有一段距离.我正在尝试制作一个可以搜索以下字段的搜索表单:项目名称、客户、ID、行业、角色、技术、项目所有者、状态、开始日期、结束日期和关键字.搜索表单将有文本框或下拉菜单,具体取决于用户搜索的字段.我想链接每个字段并一次性搜索它们.之前,我只是以project_name和client为例,方便大家理解我的代码.希望你现在能明白我在做什么.

解决方案

您可以创建一个名为 search 的新控制器.

您的搜索表单:

<%= form_tag search_index_path, method: :get do %><%= text_field_tag :project, params[:project] %><%= text_field_tag :client, params[:client] %><%= submit_tag "搜索",名称:nil %><%结束%>

包含在你的 routes.rb 中:

获取搜索/索引"

您的搜索控制器:

def 索引#存储与搜索名称匹配的所有项目@projects = Project.where("name LIKE ?", "%#{params[:project]}%")#存储与搜索到的名称匹配的所有客户端@clients = Client.where("name LIKE ?", "%#{params[:client]}%")结尾

现在您可以在索引视图中使用 @projects@clients.

小心点,因为如果搜索没有匹配项,这些变量可能会变为 nil.

EDIT - 我假设你有两个模型 ProjectClient - 如果你不能创建一个新的控制器,你可以创建搜索操作在您当前的控制器中.

定义搜索#存储与搜索名称匹配的所有项目@projects = Project.where("name LIKE ?", "%#{params[:project]}%")#存储与搜索到的名称匹配的所有客户端@clients = Client.where("name LIKE ?", "%#{params[:client]}%")结尾

然后您可以在搜索视图中使用 @projects@clients.

如果您想在其他地方显示结果(例如 index 视图),您只需将上面的内容移动到正确的操作即可.

 定义索引....#存储与搜索名称匹配的所有项目@projects = Project.where("name LIKE ?", "%#{params[:project]}%")#存储与搜索到的名称匹配的所有客户端@clients = Client.where("name LIKE ?", "%#{params[:client]}%")结尾

EDIT 2 - 好的,您正在尝试按同一模型中的字段组合进行搜索:

您并更改搜索方法以添加这两个字段:

def self.search(search_project, search_client)返回范围除非search_project.present?||search_client.present?where(['project_name LIKE ? AND client LIKE ?', "%#{search_project}%", "%#{search_client}%"])结尾

但请注意,如果您的 search_project OR search_client 不存在,|| 将返回范围,如果您愿意,可以更改为 AND (&&).

此外,AND 仅在两者匹配时才会返回,我的意思是搜索的组合...如果您愿意,您也可以将其更改为 OR.>

有搜索表单:

您的搜索表单:

<%= form_tag search_index_path, method: :get do %><%= text_field_tag :project, params[:project] %><%= text_field_tag :client, params[:client] %><%= submit_tag "搜索",名称:nil %><%结束%>

然后您的控制器必须将组合发送给模型:

@project_search = Project.search(params[:project], params[:client]).all

我认为它会解决问题...

I'm having trouble understanding the best way to make a advanced search form. I have had a good search on the internet, looking at some ways, but I can't get them to work, as most of the suggestions are outdated. I have asked a question already, but I think I was too specific and I wasn't able to fix my problem. I am wanting to search on different text boxes and drop down boxes with one search button.

EDIT2:

projects_controller:

def index
    @projects = Project.all

respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => @projects }
    end
  end

def search
@project_search = Project.search(params[:search]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 2, :page => params[:page])


end




  # GET /projects/1
  # GET /projects/1.json
  def show
    @project = Project.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @project }
    end
  end

  # GET /projects/new
  # GET /projects/new.json
  def new
    @project = Project.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @project }
    end
  end

  # GET /projects/1/edit
  def edit
    @project = Project.find(params[:id])
  end

  # POST /projects
  # POST /projects.json
  def create

    @project = Project.new(params[:project])


    @project.client = params[:new_client] unless params[:new_client].blank?
    @project.exception_pm = params[:new_exception_pm] unless params[:new_exception_pm].blank?
    @project.project_owner = params[:new_project_owner] unless params[:new_project_owner].blank?
    @project.role = params[:new_role] unless params[:new_role].blank?
    @project.industry = params[:new_industry] unless params[:new_industry].blank?
    @project.business_div = params[:new_business_div] unless params[:new_business_div].blank?

    respond_to do |format|
      if @project.save
        format.html { redirect_to @project, notice: 'Project was successfully created.' }
        format.json { render json: @project, status: :created, location: @project }
      else
        format.html { render action: "new" }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /projects/1
  # PUT /projects/1.json
  def update
    @project = Project.find(params[:id])

    respond_to do |format|
      if @project.update_attributes(params[:project])
        format.html { redirect_to @project, notice: 'Project was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /projects/1
  # DELETE /projects/1.json
  def destroy
    @project = Project.find(params[:id])
    @project.destroy

    respond_to do |format|
      format.html { redirect_to projects_url }
      format.json { head :no_content }
    end
  end




private

  helper_method :sort_column, :sort_direction
  def sort_column
    Project.column_names.include?(params[:sort]) ? params[:sort] : "project_name"
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end
end

Search View:

<h1>Search</h1>

<%= form_tag search_path, method: :get do %>
<%= hidden_field_tag :direction, params[:direction] %>
  <%= hidden_field_tag :sort, params[:sort] %>
  <%= text_field_tag :project_name, params[:project_name] %>
  <%= text_field_tag :client, params[:client] %>
  <%= submit_tag "Search", name: nil %>
<% end %>



<table class = "pretty">
<table border="1">
  <tr>
    <th><%= sortable "project_name", "Project name" %> </th>
    <th><%= sortable "client", "Client" %></th>
    <th>Exception pm</th>
    <th>Project owner</th>
    <th>Tech</th>
    <th>Role</th>
    <th>Industry</th>
    <th>Financials</th>
    <th>Business div</th>
    <th>Status</th>
    <th>Start date</th>
    <th>End date</th>
<% if false %>
    <th>Entry date</th>
    <th>Edited date</th>
    <th>Summary</th>
    <th>Lessons learned</tStackh>
    <th>Customer benifits</th>
    <th>Keywords</th>
    <!th></th>
    <!th></th>
    <!th></th>
<% end %>
  </tr>

<% @project_search.each do |t| %>
  <tr>
    <td><%= t.project_name %></td>
    <td><%= t.client %></td>
    <td><%= t.exception_pm %></td>
    <td><%= t.project_owner %></td>
    <td><%= t.tech %></td>
    <td><%= t.role %></td>
    <td><%= t.industry %></td>
    <td><%= t.financials %></td>
    <td><%= t.business_div %></td>
    <td><%= t.status %></td>
    <td><%= t.start_date %></td>
    <td><%= t.end_date %></td>
<% if false %>
    <td><%= t.entry_date %></td>
    <td><%= t.edited_date %></td>
    <td><%= t.summary %></td>
    <td><%= t.lessons_learned %></td>
    <td><%= t.customer_benifits %></td>
    <td><%= t.keywords %></td>
<% end %>
    <!td><%#= link_to 'Show', project %></td>
    <!td><%#= link_to 'Edit', edit_project_path(project) %></td>
    <!td><%#= link_to 'Destroy', project, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>
</table>

<br />
<%= will_paginate (@project_search) %>


<%= button_to "Search Again?", search_path, :method => "get" %>

<%# end %>
<%= button_to "Home", projects_path, :method => "get" %>

Project.rb

class Project < ActiveRecord::Base
  attr_accessible :business_div, :client, :customer_benifits, :edited_date, :end_date, :entry_date, :exception_pm, :financials, :industry, :keywords, :lessons_learned, :project_name, :project_owner, :role, :start_date, :status, :summary, :tech

validates_presence_of :business_div, :client, :customer_benifits, :end_date, :exception_pm, :financials, :industry, :keywords, :lessons_learned, :project_name, :project_owner, :role, :start_date, :status, :summary, :tech



def self.search search_term
 return scoped unless search_term.present?
 where find(:all, :conditions => ['project_name OR client LIKE ?', "%#{search_term}%"])
end

end

Routes:

FinalApp::Application.routes.draw do
resources :projects
match "search" => "projects#search", :as => :search
root :to => 'projects#index'
end

As you can see, I'm still a fair bit away from having a finished application. I am trying to make a search form that will be able to search on the following fields: Project name, Client, ID, Industry, Role, Technology, Project Owner, Status, Start Date, End Date, and Keywords. The search form would have either text boxes or drop down menus depending on which field the user was searching for. I am wanting to chain each field and search on them all in one go. Before, I was only using project_name, and client as examples to make it easier for you to understand my code. Hopefully you can see now what I am trying to do.

解决方案

You can create a new controller called search.

Your search form:

<%= form_tag search_index_path, method: :get do %>
  <%= text_field_tag :project, params[:project] %>
  <%= text_field_tag :client, params[:client] %>
  <%= submit_tag "Search", name: nil %>
<% end %>

incude in your routes.rb:

get "search/index"

your search controller:

def index
  #store all the projects that match the name searched
  @projects = Project.where("name LIKE ? ", "%#{params[:project]}%")  
  #store all the clients that match the name searched    
  @clients = Client.where("name LIKE ? ", "%#{params[:client]}%")
end

Now you can play with @projects and @clients in the index view.

Just be careful, because these variables might became nil if there is no match for the search.

EDIT - I am assuming you have two models Project and Client - if you cannot create a new controller you can create the search action in your current controller.

def search
  #store all the projects that match the name searched
  @projects = Project.where("name LIKE ? ", "%#{params[:project]}%")  
  #store all the clients that match the name searched    
  @clients = Client.where("name LIKE ? ", "%#{params[:client]}%")
end

And than you can use the @projects and @clients in the search view.

If you are trying to display the results in somewhere else (for example index view), you can just move the above to the correct action.

 def index
  ....
  #store all the projects that match the name searched
  @projects = Project.where("name LIKE ? ", "%#{params[:project]}%")  
  #store all the clients that match the name searched    
  @clients = Client.where("name LIKE ? ", "%#{params[:client]}%")
end

EDIT 2 - OK, you are trying to search by a combination of fields in the same model:

You and change your search method to add these two fields:

def self.search(search_project, search_client) 
  return scoped unless search_project.present? || search_client.present?
  where(['project_name LIKE ? AND client LIKE ?', "%#{search_project}%", "%#{search_client}%"])
end

But please note the || will return scope if your search_project OR search_client are not present, you can change for AND (&&) if you prefer.

Also, the AND will return only if both match, I mean the combination of search... You can also change it to OR if you want.

Having the search form:

Your search form:

<%= form_tag search_index_path, method: :get do %>
  <%= text_field_tag :project, params[:project] %>
  <%= text_field_tag :client, params[:client] %>
  <%= submit_tag "Search", name: nil %>
<% end %>

Then your controller must send the combination to the model:

@project_search = Project.search(params[:project], params[:client]).all

I think it will solve the problem...

这篇关于Ruby on Rails:高级搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆