Ransack不考虑参数

时间:2015-02-04 20:35:44

标签: ruby-on-rails ruby ransack

我正在尝试为名为Space的对象创建搜索表单。我尝试过使用了很多ifelsif,我意识到它不起作用所以我开始查看Ransack。看起来很棒,如果可以让它发挥作用。

问题是,我的第一页上有我的表格,home#index。在所有教程中,表单都显示在同一页面上,我想转到spaces#index,所以这里是我的代码......

主页(index.html.erb)

<div class="col-md-12 text-center">
    <%= search_form_for @q, class: "form-inline" do |f| %>
        <div class="input-append">
            <%= f.label :city %>
            <%= f.search_field :city %>
    <div class="row">
        <button class="btn" type="submit"><i class="fa fa-search"></i></button>
    </div>
    </div>
<% end %>
</div>

HomeController.rb

class HomeController < ApplicationController
  def index
  @q = Space.search(params[:q])
  @spaces = Space.all
  @spaceimages = Spaceimage.all
  @spacetypes = @spaces.select(:spacetype).distinct
  end
end

SpacesController.rb

def index
  @q = Space.search(params[:q])
  @spaces = @q.result
end

这就是服务器获得的内容:

Started GET "/spaces?utf8=%E2%9C%93&q%5Bcity%5D=Gothenburg" for 127.0.0.1 at 2015-02-04 21:32:44 +0100
Processing by SpacesController#index as HTML
  Parameters: {"utf8"=>"✓", "q"=>{"city"=>"Gothenburg"}}
  Space Load (0.2ms)  SELECT `spaces`.* FROM `spaces`
  Rendered spaces/index.html.erb within layouts/application (1.2ms)
  User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
Completed 200 OK in 52ms (Views: 50.7ms | ActiveRecord: 0.4ms)

所以params在那里,但@spaces.search(或.ransack)对查询没有任何作用。为什么呢?

1 个答案:

答案 0 :(得分:0)

其他人在看这个: 确保谓词作为查询哈希的键传入,即使您定义了model.ransackable_attributes。

像这样(first_name_cont是这里的谓词):

>> User.ransack(first_name_cont: 'Rya').result.to_sql
=> SELECT "users".* FROM "users"  WHERE ("users"."first_name" LIKE '%Rya%')
相关问题