【发布时间】:2015-02-04 20:35:43
【问题描述】:
我正在尝试为名为@987654321@ 的对象创建搜索表单。我尝试过使用很多if 和elsif,但我意识到它不起作用,所以我开始检查 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)
所以参数在那里,但@spaces.search(或.ransack)对查询没有任何作用。为什么?
【问题讨论】:
-
您是否尝试过使用一些表单助手,例如
f.search_field :city_eq。您的Space模型中是否还实现了self.ransackable_attributes? (如果不是这很好,但如果是这样,请发布,因为这可能会导致 ransack 忽略搜索参数。 -
其实就是这样! _cont 或类似的必须添加到 search_field 中,否则它不会接受它。非常感谢! :) @engineersmnky
标签: ruby-on-rails ruby ransack