Rails search functionality

我是研究僧i 提交于 2019-12-03 21:55:46
TheDelChop

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.

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

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