表单标签在Rails5上无法正确路由

时间:2019-11-02 06:13:56

标签: ruby-on-rails ruby

我想做什么:

在Rails上实现搜索表单。 如果用户单击搜索按钮,rails将从文本输入中读取值并将其作为查询传递。 当我单击按钮时,它应该转到 localhost / internships / search / keyword?keyword = blahblah

出了什么问题

但是,每当我单击按钮时,它就会转到 localhost?keyword = blahblah

我做了什么:

这是我的代码

search_controller.rb

<div class="input-group">
    <%= form_tag internships_keyword_search_path, method: :get do %>
        <%= text_field_tag :keyword, params[:keyword], placeholder: "Search query", class: "form-control" %>
        <%= submit_tag "search", name: nil, class: "btn btn-danger wrn-btn" } %>
    <% end %>
</div>

routes.rb

get '/internships/search/keyword', to: 'internships_search#search_keyword', as: 'internships_keyword_search'

更新

1。 search_keyword的内容

def search_keyword
        @internships = Internship.where("subject LIKE :keyword OR content LIKE :keyword", keyword: params[:keyword]).all
        if @internships.length == 0 then
            render :empty
        else
            render :show
        end
end

2。当我将form_tag更改为link_to时,它正在工作。但是button_to不是。

3。 nginx配置

upstream rails_app {
  server app:3000;
}

server {
  # define your domain
  server_name www.example.com;

  # define the public application root
  root   $RAILS_ROOT/public;
  index  index.html;

  # define where Nginx should write its logs
  # access_log $RAILS_ROOT/nginx.access.log;
  # error_log $RAILS_ROOT/nginx.error.log;

  # deny requests for files that should never be accessed
  location ~ /\. {
    deny all;
  }

  location ~* ^.+\.(rb|log)$ {
    deny all;
  }

  # serve static (compiled) assets directly if they exist (for rails production)
  location ~ ^/(assets|images|javascripts|stylesheets|swfs|system)/ {
    try_files $uri @rails;

    access_log off;
    gzip_static on; # to serve pre-gzipped version

    expires max;
    add_header Cache-Control public;

    # Some browsers still send conditional-GET requests if there's a
    # Last-Modified header or an ETag header even if they haven't
    # reached the expiry date sent in the Expires header.
    add_header Last-Modified "";
    add_header ETag "";
    break;
  }

  # send non-static file requests to the app server
  location / {
    try_files $uri @rails;
  }

  location @rails {
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://rails_app;
  }
}

2 个答案:

答案 0 :(得分:0)

尝试

 <%= form_tag("/internships/search/keyword", method: "get") do %>

如果这行不通,请解释提交表单时您的操作所要使用的参数

答案 1 :(得分:0)

自我回答:问题是嵌套表格。 我的html.erb完整代码是

<form ...>
    <div class="input-group">
        <%= form_tag internships_keyword_search_path, method: :get do %>
            <%= text_field_tag :keyword, params[:keyword], placeholder: "Search query", class: "form-control" %>
            <%= submit_tag "search", name: nil, class: "btn btn-danger wrn-btn" } %>
        <% end %>
    </div>
</form>

外部form标签在form_tag内部阻塞。