복붙노트

[RUBY-ON-RAILS] 루비 온 레일즈 : 고급 검색

RUBY-ON-RAILS

루비 온 레일즈 : 고급 검색

나는 데 문제가 고급 검색 양식을 할 수있는 최선의 방법을 이해하는 데 문제가 있습니다. 나는 어떤면을보고, 인터넷에서 좋은 검색을했다,하지만 제안의 대부분은 구식이되어 나는이 일에 그들을 얻을 수 없습니다. 나는 이미 질문을했다,하지만 난 너무 구체적라고 생각하고 내 문제를 해결 할 수 없습니다. 나는 다른 텍스트 상자에 검색 한 검색 버튼으로 상자를 드롭 다운하고자하고있다.

Aaditi :

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

보기를 검색 :

<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

경로 :

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

당신이 볼 수 있듯이, 나는 공정이 완성 된 응용 프로그램을 가지고 멀리 비트 여전히입니다. 프로젝트 이름, 클라이언트, ID, 산업, 역할, 기술, 프로젝트 소유자, 상태, 시작 날짜, 종료 날짜 및 키워드 : 나는 다음과 같은 필드에 검색 할 수 있습니다 검색 양식을 만들려고 노력하고 있습니다. 검색 양식 중 하나를 텍스트 상자이 있거나 사용자가 검색 한 필드에 따라 드롭 다운 메뉴를 것입니다. 나는 사슬에 각 필드를 원하는하고 한 번에 모두 검색하고 있습니다. 전에, 난 단지 당신이 내 코드를 쉽게 이해할 수 있도록 예제로 프로젝트 이름 및 클라이언트를 사용했다. 희망 당신은 내가 뭘하려고 오전 지금 볼 수 있습니다.

해결법

  1. ==============================

    1.당신은 검색이라는 새로운 컨트롤러를 만들 수 있습니다.

    당신은 검색이라는 새로운 컨트롤러를 만들 수 있습니다.

    검색 양식 :

    <%= 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 %>
    

    당신의 routes.rb에 포함 :

    get "search/index"
    

    검색 컨트롤러 :

    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
    

    지금 당신은 인덱스보기 @projects 및 @clients로 재생할 수 있습니다.

    검색에 대한 일치가없는 경우이 변수가 nil이되었다 수 있기 때문에 그냥주의해야합니다.

    편집 - 새 컨트롤러를 작성할 수없는 경우 당신은 당신의 현재 컨트롤러의 검색 작업을 만들 수 있습니다 - 당신이 두 모델 프로젝트 및 클라이언트가 가정입니다.

    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
    

    그리고 당신은 검색보기에서 @projects 및 @clients을 사용할 수있는 것보다.

    당신이 다른 곳에서 결과를 표시하려는 경우 (예를 들어, 인덱스보기 위해), 당신은 단지 올바른 행동 위를 이동할 수 있습니다.

     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
    

    편집 2 - OK, 당신은 같은 모델의 필드의 조합에 의해 검색하려고 :

    당신과 당신의 검색 방식을 변경하여이 두 필드를 추가합니다 :

    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
    

    그러나주의하시기 바랍니다 || 당신의 SEARCH_PROJECT 또는 search_client이 존재하지 않는 경우 범위를 반환합니다, 당신은 AND (&&) 당신이 원하는 경우에 대해 변경할 수 있습니다.

    단지 모두 일치하는 경우, 내가 검색의 조합을 의미 또한, AND 돌아갑니다 ... 당신은 또한 또는 당신이 원하는 경우 변경할 수 있습니다.

    탐색 양식을 갖는 :

    검색 양식 :

    <%= 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 %>
    

    그런 다음 컨트롤러는 모델 조합을 보내야합니다 :

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

    나는이 문제를 해결할 것이라고 생각 ...

  2. ==============================

    2.난 내 응용 프로그램에서 수 MetaSearch를 사용하고 아주 편리하다고했습니다. 당신이 이미 간주 한 경우, 어떤 문제가 당신이 있었나요?

    난 내 응용 프로그램에서 수 MetaSearch를 사용하고 아주 편리하다고했습니다. 당신이 이미 간주 한 경우, 어떤 문제가 당신이 있었나요?

    더듬다는 수 MetaSearch의 후계자입니다, 같은 저자에 의해도 있습니다.

  3. ==============================

    3.이 캐스트를 레일에 간단한 설명을 찾을 수 있습니다

    이 캐스트를 레일에 간단한 설명을 찾을 수 있습니다

    params 객체를 파라미터로 특정 필드를 포함하고 필터를 만드는 경우 기본적으로, 우리는 시험에 있습니다. 아래의 예를 참조하십시오 :

    def find_products
      products = Product.order(:name)
      products = products.where("name like ?", "%#{keywords}%") if keywords.present?
      products = products.where(category_id: category_id) if category_id.present?
      products = products.where("price >= ?", min_price) if min_price.present?
      products = products.where("price <= ?", max_price) if max_price.present?
      products
    end 
    

    대안은 더듬다입니다. 더듬다 레일 응용 프로그램에 루비 모두 간단하고 고급 검색 형태를 만들 수 있습니다

  4. from https://stackoverflow.com/questions/11609005/ruby-on-rails-advanced-search by cc-by-sa and MIT license