Rails search functionality

跟風遠走 提交于 2019-12-21 06:40:58

问题


I am taking a rails class at my University and I am trying to create a search form which will show the results on the same page rather than show a different page of results. Is this something simple to do? I am creating a museum app with artifacts for each museum but I want the user to search artifacts from either page.

On my routes.rb I have

resources :artifacts do
    collection do
        get 'search'
    end
  end

On my museum index I have the code below that he gave us but not sure how to tweak the get routes for the same page.

<%= form_tag search_artifacts_path, :method => 'get' do %>

    <p>
    <%= text_field_tag :search_text, params[:search_text] %>
    <%= submit_tag 'Search' %>
    </p>

<% end %>

<% if @artifacts %>
    <p> <%= @artifacts.length %> matching artifacts. </p>

    <h2> Matching Artifacts </h2>
    <% @artifacts.each do |a| %>

        <%= link_to "#{a.name} (#{a.year})", a %><br />

    <% end %>

<% end %>

回答1:


Yes, this is easy. Just have the index page return the search results if params[:search_text] is present - this way you don't need a new route or a different page.

class ArtifactsController < ApplicationController
  def index
    @artifacts = Artifact.search(params[:search_text])
  end    
end

class Artifact < ActiveRecord::Base
  def self.search(query)
    if query
      where('name ILIKE ?', "%#{query}%")
    else
      all
    end
  end
end

So then your form looks like:

<%= form_tag artifacts_path, :method => 'get' do %>
  <p>
   <%= text_field_tag :search_text, params[:search_text] %>
   <%= submit_tag 'Search' %>
  </p>
<% end %>

Edit:

So what you really want to do is any page you want to search, include a form which makes a request to that same page.

Then in each of those controller methods just put this line of code:

    @artifacts = Artifact.search(params[:search_text])

and that will populate the @artifcats array with only artifacts that match the search query.




回答2:


Try using "Ransack" gem. It can also perform some more powerful searches.



来源:https://stackoverflow.com/questions/9489733/rails-search-functionality

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