pg_search使用一个文本字段和一个类别选择类型字段

时间:2012-06-04 22:27:24

标签: ruby-on-rails ruby-on-rails-3 postgresql pg-search

Ruby on Rails新手。我尝试使用pg_search gem但遇到了一些困难(是的,我正在查看文档)。我想要一个既有文本字段又有选择字段(类别)的搜索表单。这是我到目前为止的代码:

contact_info.rb

class ContactInfo < ActiveRecord::Base
...
include PgSearch
  pg_search_scope :search_by_category, (lambda do |category, query|
  raise ArgumentError unless [:prev, :cat].include?(category)
  {
      :against => category,
      :query => query
  }
  end
end

home_controller.rb

class HomeController < ApplicationController
  def index
    @contact_infos = ContactInfo.search_by_category(params[:query])
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @contact_infos }
    end
end

主\ index.html.erb

<%= form_for :search_by_category, :url => {:controller => 'home', :action => 'index'},
  :html => {:method => 'get'} do |f| %>

  <%= text_field_tag :query %>
  <%= f.label :category_id, "Category" %>
  <%= f.collection_select :category_id, Category.all,
                        :id, :name,
                        {:prompt => 'All'} %>
  <br/>
  <%= f.submit "Search" %>
<% end %>

我收到了这个错误:

ArgumentError in HomeController#index wrong number of arguments (1 for 2)

...

请求

参数:

{"utf8"=>"✓","query"=>"test","search_by_category"=>{"category_id"=>"2"},"commit"=>"Search"}

我理解问题出在这一行:

@contact_infos = ContactInfo.search_by_category(params[:query])

但我不确定如何从视图中传递两个变量(home \ index.html.erb)。

谢谢!

1 个答案:

答案 0 :(得分:4)

好的 - 我明白了。如果有人帮助......

在模型contact_info.rb

class ContactInfo < ActiveRecord::Base
  include PgSearch

 ...
  pg_search_scope :search_by_category, :against => :previous_value
  scope :in_category, lambda { |category_id|
    where(:category_id => category_id)
  }
end

在控制器home_controller.rb

class HomeController < ApplicationController
  def index

  if params[:search_by_category].nil?
    @contact_infos = ContactInfo.search(params[:query])
  else
    tmp = params[:search_by_category]
    @contact_infos = ContactInfo.search_by_category(params[:query]).in_category(tmp[:category_id])
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @contact_infos }
    end
  end
 end
end

在视图home \ index.html.erb

...
    <%= form_for :search_by_category, :url => {:controller => 'home', :action => 'index'}, :html => {:method => 'get'} do |f| %>
    <%= text_field_tag :query %>
    <%= f.label :category_id, "Category" %>
    <%= f.collection_select :category_id, Category.all,
                            :id, :name,
                            {:prompt => 'All'} %>
    <br/>
    <%= f.submit "Search" %>
<% end %>
...