Nerdysyntax
Nerdysyntax

Reputation: 365

Rails search functionality

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

Upvotes: 0

Views: 2120

Answers (2)

pk-n
pk-n

Reputation: 576

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

Upvotes: 0

TheDelChop
TheDelChop

Reputation: 7998

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.

Upvotes: 3

Related Questions