带有post请求和有效负载(json对象)的rails link_to

时间:2019-07-13 04:03:37

标签: ruby-on-rails

我想使用link_to链接和有效负载将发布请求从一个路由(主路由)发送到另一条路由,以便将获得此请求的控制器访问json文件(或从DB提取的另一个数据)我当前的rails link_to代码是:

<%= link_to "{{product}}", controller: 'main', action: 'product', payload: 'msg', method: :post , tabindex:14 %>

传递有效负载:“ msg”作为GET请求参数! 在浏览器路径上看到的是:

http://localhost:3000/product?method=post&payload=msg&tabindex=14

我想做的是在POST请求中发送有效载荷,而没有在屏幕上看到参数。 另一个问题-我不想发送“ msg”,而是查询数据库(例如Product.find(1))和要作为有效载荷发送的结果。我以后如何访问该对象?

1 个答案:

答案 0 :(得分:1)

# routes.rb
Rails.application.routes.draw do
  get 'users/index'
  post '/post', to: 'users#post'
  root to: 'users#index'  
end
<% # index.html.erb %>
<%= link_to_post 'Post Link', '/post', {foo: :bar, bar: :foo, json: { qux: :baz}.to_json} %>
<% # post.html.erb %>
<h1>Posted</h1>
params.inspect: <%= params.inspect %>
<br />
<br />
<%= link_to 'Go back', '/' %>
# application_helper.rb
module ApplicationHelper
  def link_to_post(body, url, params = {})
    form_tag url do |f|
      params.each do |key, value|
        concat hidden_field_tag(key, value)
      end
      concat link_to(
        body,
        '#',
        onclick: '$(this).closest("form").submit(); return false;'
      )
    end
  end
end
<% # application.html.erb %>
<!DOCTYPE html>
<html>
  <head>
    <%= javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js' %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

enter image description here

enter image description here


或者您可以使用AJAX发送POST任务

<!DOCTYPE html>
<html>
  <head>
    <%= javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js' %>
    <%= javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/noty/3.1.0/noty.js' %>
    <%= stylesheet_link_tag 'https://cdnjs.cloudflare.com/ajax/libs/noty/3.1.0/noty.min.css' %>

    <script type="text/javascript">
      $(function() {
        $('.sendAjaxPostRequest').click(function() {
          $.ajax({
            url: "/post",
            method: "POST",
            data: {
              json: $(this).data('json')
            }
          }).done(function() {
            new Noty({
              text: "Data was successfully submitted to server via AJAX",
              type: "success"
            }).show();
          }).fail(function() {
            new Noty({
              text: "Couldn't send data",
              type: "error"
            }).show();
          });
        })
      });      
    </script>
  </head>
  <body>
    <%= link_to 'Send POST request with ajax', '#', class: 'sendAjaxPostRequest', data: { json: { foo: 'bar' }.to_json } %>

    <!-- It will render
    <a class="sendAjaxPostRequest" data-json="{&quot;foo&quot;:&quot;bar&quot;}" href="#">Send POST request with ajax</a>
    -->
  </body>
</html>
Rails.application.routes.draw do
  get 'users/index'
  post '/post', to: 'users#post'
  root to: 'users#index'  
end
class UsersController < ApplicationController
  skip_before_action :verify_authenticity_token

  def post
    Rails.logger.info("params[:json]: #{params[:json]})")
    render json: { status: 'success' }
  end
end

enter image description here