Rails不处理params

时间:2011-01-31 07:38:30

标签: ruby-on-rails activerecord

我正在尝试实施高级搜索。

我在模型中有这个:

def self.filter(params)
params.inject(self) do |scope, (key, value)|
  return scope if value.blank?
  case key
    when :min_size
      scope.scoped(:conditions => ["size >= ?", value])
    when :max_size
      scope.scoped(:conditions => ["size <= ?", value])
    else
      scope.scoped(:conditions => ["created_at > ?", 4.weeks.ago]) 
  end
end
end

这是在我的控制器中:

  def search
    @listings = Listing.filter(params)
    respond_to (:html)
  end

我用这个表格搜索:

<%= form_tag '/search', :method => "get" do |f|  %>
    <%= text_field_tag :min_size, params[:min_size] %>
    <%= text_field_tag :max_size, params[:max_size] %>
    <%= submit_tag "Search", :name => nil %>
<% end %>

当我试图搜索Rails时,似乎忽略了所有传递的参数并找到了最后一个案例切换的所有条目(“created_at&gt;?”,4.weeks.ago)。然而,参数通过:

 Started GET "/search?utf8=%E2%9C%93&min_rent=10&max_rent=35" for 127.0.0.1 at Mon Jan 31 12:25:40 +0500 2011
 Processing by ListingsController#search as HTML
 Parameters: {"utf8"=>"✓", "min_size"=>"40", "max_size"=>"50"}
 Listing Load (1.1ms)  SELECT "listings".* FROM "listings" WHERE (created_at > '2011-01-03 07:25:40.978742') AND (created_at > '2011-01-03 07:25:40.980977') AND (created_at > '2011-01-03 07:25:40.982080') AND (created_at > '2011-01-03 07:25:40.983077') AND (created_at > '2011-01-03 07:25:40.984138')

这可能是什么问题?在控制台中它可以正常工作

>> some = Listing.filter(:min_size => 40, :max_size => 50)
=> [#<Listing id: 1, title: "1 br apartment, Paris 16e", address: "1 Rue Monsieur-le-Prince", district: "Paris 6e", size: 42, rent: 2000, created_at: "2011-01-26 18:30:57", updated_at: "2011-01-26 19:00:44">]

2 个答案:

答案 0 :(得分:2)

我猜这个问题是开关案例比较:

case key

我认为从注入密钥是“min_size”而不是:min_size,这就是为什么它总是转到else分支。

编辑:

尝试将代码更改为

when "min_size"
  scope.scoped(:conditions => ["size >= ?", value])
when "max_size"
  scope.scoped(:conditions => ["size <= ?", value])

它应该有效。也许:))

答案 1 :(得分:0)

您可以使用Searchlogic gem完成此操作。

使用Searchlogic,您可以执行大于/小于搜索的内容:

irb> Listing.search(:size_gt => 10, :size_lt => 100)

在您的控制器中:

def index
  @search = Listing.search(params[:search])
end
在您看来

<%= form_for @search do |f|  %>
  <%= f.text_field :size_gt %>
  <%= f.text_field :size_lt %>
  <%= f.submit "Search" %>
<% end %>

网址看起来像这样

/listings?search[size_gt]=10&search[size_lt]=100