form_with执行动作但无法正确呈现页面

时间:2019-05-02 02:49:09

标签: ruby-on-rails

我正在使用一个简单的搜索功能,该功能位于用户仪表板视图(它也具有自己的仪表板控制器)中。现在,搜索功能在单个模型上运行,并且在执行操作后,应该转到该特定模型的索引页。但是,索引页在搜索后不会呈现,即使日志显示它已重定向到索引页,它仍保留在仪表板页中。

这是日志:

Started GET "/detected_vehicles?utf8=%E2%9C%93&%3Aq%5Blocation_eq%5D=1&commit=Search" for 127.0.0.1 at 2019-05-02 10:33:08 +0800
Processing by DetectedVehiclesController#index as JS
  Parameters: {"utf8"=>"✓", ":q"=>{"location_eq"=>"1"}, "commit"=>"Search"}
  Rendering detected_vehicles/index.html.slim within layouts/application
  Rendered shared/_flash.html.slim (3.1ms)
  Rendered detected_vehicles/index.html.slim within layouts/application (80.9ms)
  Rendered layouts/_navbar.html.slim (2.9ms)
  Rendered layouts/_footer.html.slim (3.6ms)
Completed 200 OK in 326ms (Views: 271.7ms | ActiveRecord: 6.4ms)

这是我的form_with代码:

    = form_with url: detected_vehicles_path, method: :get, class: 'ui form' do |f|
        .field
            = select_tag(":q[location_eq]", options_from_collection_for_select(Camera.all, "id", "full_location"), class: 'form-control', id: 'detected_vehicle')
        = f.submit 'Search', class: 'form-control'

我尝试使用form_tag做同样的事情,它按预期工作。这是我使用form_tag的代码:

    = form_tag detected_vehicles_path, method: :get, class: 'ui form' do
        .field
            = select_tag(":q[location_eq]", options_from_collection_for_select(Camera.all, "id", "full_location"), class: 'form-control', id: 'detected_vehicle')
        = submit_tag 'Search', class: 'form-control'

虽然我知道我现在可以使用form_tag解决方案,但我想找出我构建form_with的方式出了什么问题,因为自从那以后它可能很快成为编写表单的标准据我所读,form_tagform_for在技术上已被弃用。

1 个答案:

答案 0 :(得分:1)

如果仔细观察,使用form_with时,您使用的是JS:

Processing by DetectedVehiclesController#index as JS

因为form_with设置了local: false by default

  

:local-默认情况下,表单提交是远程XHR。使用local: true禁用远程提交。

因此,将local: true添加到form_with并查看会发生什么情况。