Ruby Rails select2 提交无效

Ruby on Rails select2 submit doesn't work

  https://select2.org/getting-started/basic-usage

我想像上面 link 中的第一个示例一样搜索 Post 标题。

代码:

<!-- search -->
      <div class="card my-auto">
        <%= form_with url: posts_path, method: :get, local: :true do |f| %>
          <div class="card-body">
            <p>Search for a Post title.</p>
            <%= f.collection_select(:post_id, Post.all, :id, :title, {include_blank: 'Post titles'}, {class:'selectbooktitle form-control'}) %>
            <hr>
            <div class="input-group">
                <span class="input-group-btn">
                  <%= f.submit 'Search', class: 'btn btn-outline-success'%>

                </span>
        <% end %>
        </div>
        </div>
      </div>

这是单击“提交”时来自我的服务器的请求。

Started GET "/posts?utf8=%E2%9C%93&post_id=16&commit=Search" for 127.0.0.1 at 2018-05-09 14:18:51 +0200
Processing by PostsController#index as HTML
  Parameters: {"utf8"=>"✓", "post_id"=>"16", "commit"=>"Search"}
  Rendering posts/index.html.erb within layouts/application
  Post Load (0.3ms)  SELECT "posts".* FROM "posts"
  Post Load (0.3ms)  SELECT "posts".* FROM "posts" ORDER BY created_at DESC
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" =  LIMIT   [["id", 2], ["LIMIT", 1]]
  CACHE User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" =  LIMIT   [["id", 2], ["LIMIT", 1]]
  CACHE User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" =  LIMIT   [["id", 2], ["LIMIT", 1]]
  CACHE User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" =  LIMIT   [["id", 2], ["LIMIT", 1]]
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" =  LIMIT   [["id", 1], ["LIMIT", 1]]
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" =  LIMIT   [["id", 4], ["LIMIT", 1]]
  Rendered posts/index.html.erb within layouts/application (10.2ms)
  Category Load (0.3ms)  SELECT "categories".* FROM "categories"
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" =  ORDER BY "users"."id" ASC LIMIT   [["id", 2], ["LIMIT", 1]]
  Rendered layouts/_navbar.html.erb (4.5ms)
  Rendered layouts/_alerts.html.erb (0.4ms)
  Rendered layouts/_footer.html.erb (0.6ms)
Completed 200 OK in 59ms (Views: 55.0ms | ActiveRecord: 1.9ms)

导致这个URL:

http://localhost:3000/posts?utf8=%E2%9C%93&post_id=20&commit=Search

它应该导致以下 URL:

http://localhost:3000/posts/20

我做错了什么?

提前感谢您的帮助!

Rails框架把你送到那个URL并没有错,因为你设置了form_with:url posts_path 的选项。这等于 /posts.

您要做的是根据 select 内容更改表单操作。为此,您需要 JavaScript 即时更改表单操作。

这是一个简化的例子:

app/views/some_directory/some_file.html.erb

<%= form_with url: posts_path, method: :get, local: true do |form| %>
  <% options = {include_blank: 'Post titles'} %>
  <% html_options = {
     class: 'selectbooktitle form-control', 
     'data-change-form-action-with-value': true,
  } %>

  <%= form.collection_select :post_path, Post.all, method(:post_path), :title, options, html_options %>
  <%= form.submit 'Search', class: 'btn btn-outline-success'%>
<% end %>

app/assets/javascripts/some_file.咖啡

initChangeFormActionWithValue = (selectElement) ->
  selectElement       = $(selectElement)
  closestAncestorForm = selectElement.closest('form')

  selectElement.on 'change', ->
    closestAncestorForm.attr 'action', selectElement.val()

$(document).on 'turbolinks:load', ->
  $('select[data-change-form-action-with-value="true"]')
    .each -> initChangeFormActionWithValue(this)

现在,当更改 select 值时,表单会更新为 selected 选项的值(其中包含 post 路径)。当您提交请求时,您将请求 GET /posts/:id.

Note: This is a simplified solution. Which requests GET /posts/:id of the selected post. However the values of the form are also submitted. You can leave them unhandled, but should at least know that their there. So you are not surprised when you see the post_path or submit params in the show.

Furthermore if you don't change the select at all when pressing submit you currently just request GET /posts. And if you change to select value to a post and back to 'Post titles' (the blank value), the action is cleared. Which means you get the current URL.


或者,您可以使用当前的解决方案。比在你的 PostsController#index 重定向到 PostsController#show 如果 params[:post_id] 存在。

class PostsController < ApplicationController

  def index
    return redirect_to post_path(params[:post_id]) if params[:post_id]

    # other index code
  end

end