2

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

联系信息.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)中传递这两个变量。

谢谢!

4

1 回答 1

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 %>
...
于 2012-06-06T06:35:58.050 回答