简体   繁体   中英

rails search form with pg_search

Here I would like to have one search form for different models User & Post

The result should be seen in different partial views.

The search controller is like

class SearchController < ApplicationController
  def index
    @users = User.search(params[:query])
    @posts = Post.search(params[:query])
  end
end 

So that I can use partial to see results of both users and posts

I am using pg_search, so the model is like

class User < ActiveRecord::Base
  include PgSearch
  pg_search_scope :search, :against => [:name]
end


class Post < ActiveRecord::Base
  include PgSearch
  pg_search_scope :search, :against => [:content]
end

My question is how I get the :query form search form? and to pass the :query to search controller?

  <%= form_tag(XXXXX_path, method: "get") do %>
    <%= text_field_tag :search, nil, placeholder: "Search ...", class: "form-control" %>
    <%= submit_tag "", style: "display: none;" %>
  <% end %>

What is XXXXX should be on above code to make the controller get :query? since I don't want to have another search model

Or is there any other way to have the search form?

It depends on what you want XXXXX to be called. I would recommend calling it something like search_path . You would have to make some changes though to pass :query to your controller.

In your routes.rb file you could have something like (check out the link for additional routing needs based on your code):

get '/search' => 'search#index'

In your view you are naming the param as :search , that is okay but in your controller you would have to reference params[:search] in order for it to be available.

If you want the param to be called :query you would have to change the text_field_tag to match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM