rails link_to发送get而不是post

时间:2014-03-26 11:50:34

标签: javascript ruby-on-rails

我有一些链接,我想发送POST请求,但他们正在发送get

<p class="tags">
  <% tags.keys.each do |key| %>
    <% if tags[key] == 1 %>
      <%= link_to by_tag_media_path(:tag => key), :remote => true, :method => :post do %>
        <span class="font-18"><%= key %></span>
      <% end %>
    <% elsif tags[key] == 2 %>
      <%= link_to by_tag_media_path(:tag => key), :remote => true, :method => :post do %>
        <span class="font-24"><%= key %></span>
      <% end %>
    <% elsif tags[key] == 3 %>
      <%= link_to by_tag_media_path(:tag => key), :remote => true, :method => :post do %>
        <span class="font-36"><%= key %></span>
      <% end %>
    <% end %>
  <% end %>
</p>

此链接位于部分名为_tags.html.erb的部分,在index.html.erb页面上,部分调用我有这个js代码:

function apply_filters(load_more){
          var params = "";

          $("a.selected").each(function(i, obj){
            params += $(this).text() + "/"
          });

          $("a.type_class").each(function(i, obj){
            params += $(this).text() + "/";
          });

          if(load_more){
            $.post("/media/filtered", {filters: params, load_more: true});
          } else {
            $.post("/media/filtered", {filters: params});
          }
        }

        $("#filtered_media_path").click(function(){
          apply_filters(true);
        });

当调用这个js代码时,我重新渲染_tags.html.erb部分并且链接工作正常(发送POST)但是当最初页面呈现时它们发送GET请求。渲染后的html代码在两种情况下都是相同的。

部分类表单索引页面:

<span id="cards">
    <%= render :partial => "media_cards", :locals => {:media_cards => @media_cards, :tags => @tags, :featured_cards => @featured_cards} %>
</span>

和media_cards partial:

 <div class="card media-card search hide-for-mobile">
    <input type="text" name="search-value" id="search_value"/>

    <span id="tags">
      <%= render :partial => "tags", :locals => {:tags => tags} %>
    </span>
  </div>

by_tags.js.erb:

$("#cards").html("<%= escape_javascript(render :partial => 'media_cards', :locals => {:media_cards => @media_cards, :tags => @tags, :featured_cards => @featured_cards}) %>");

生成的html看起来像:

<a href="/media/by_tag?tag=test" data-method="delete" data-remote="true" rel="nofollow">
        <span class="font-36">test</span>
</a>

2 个答案:

答案 0 :(得分:0)

这是link_to protype

link_to(body, url, html_options = {})

您正在做的是传递错误的参数 所以改变你的代码

link_to("some text", by_tag_media_path(:tag => key),  :remote => true, :method => :post)

答案 1 :(得分:0)

我建议你仔细看看。 http://guides.rubyonrails.org/working_with_javascript_in_rails.html 它帮助了我很多次。