【问题标题】:Acts_As_Votable Ajax RequestActs_As_Votable Ajax 请求
【发布时间】:2016-03-04 20:05:31
【问题描述】:

试图弄清楚如何让 ajax 与我的 Acts_As_Votable 按钮一起工作。

这就是我现在所拥有的。


post_controller.rb

def favorite
  @post = Post.find(params[:id])
  @post.upvote_from current_user
  respond_to do |format|
    format.js
  end 
end

def unfavorite 
  @post = Post.find(params[:id])
  @post.unvote_by current_user
  respond_to do |format|
   format.js
  end 
end

_post.html.erb

<% if current_user.voted_on? post  %>
  <%= link_to '<i style="color: red" class="fa fa-star"></i> Favorited'.html_safe, unfavorite_post_path(post), method: :put, remote: true, id: "unfavorite" %>
<% else %> 
  <%= link_to '<i class="fa fa-star"></i> Favorite'.html_safe, favorite_post_path(post), method: :put, remote: true, id: "favorite" %>
<% end %>

favorite.js.erb & unfavorite.js.erb

$('#favorite').html("<i style='color: red' class='fa fa-star'></i> Favorited");

$('#unfavorite').html("<i class='fa fa-star'></i> Favorite");

现在我已经部分工作了。我有两个问题。

  1. 每个页面包含多个帖子。我如何告诉 format.js.erb 文件以该特定帖子的收藏按钮为目标。现在,jQuery 只更改第一个帖子按钮,无论我在页面的哪个位置单击。我尝试将 link_to id 设置为 favorite ,然后在 format.js 文件中使用 favorite ,但这没有用。
  2. 我想更改 format.js 文件以将实际按钮放入 div 而不仅仅是更改其文本。因此,用户无需刷新页面即可切换收藏和取消收藏。我尝试将 link_to 按钮放在 .html("") 部分中,但这不起作用。我不确定如何使用 ajax 提交发布请求。

感谢您的帮助!如果您需要更多代码,或者我不清楚某些事情,请告诉我。

【问题讨论】:

    标签: javascript jquery ruby-on-rails ajax


    【解决方案1】:

    id 在一个页面中必须是唯一的。您应该能够将post.id 附加到您的链接:

    _post.html.erb

    <% if current_user.voted_on? post  %>
      <%= render 'unfavorite_link', post: post %>
    <% else %> 
      <%= render 'favorite_link', post: post %>
    <% end %>
    

    _favorite_link.html.erb

    <%= link_to '<i class="fa fa-star"></i> Favorite'.html_safe, favorite_post_path(post), method: :put, remote: true, id: "favorite-#{post.id}" %>
    

    _unfavorite_link.html.erb

    <%= link_to '<i style="color: red" class="fa fa-star"></i> Favorited'.html_safe, unfavorite_post_path(post), method: :put, remote: true, id: "unfavorite-#{post.id}" %>
    

    您可以使用replaceWith 代替仅使用 AJAX 设置的html,它会替换整个链接,而不仅仅是其内部 HTML:

    favorite.js.erb

    $('#favorite-<%= @post.id %>').replaceWith('<%= escape_javascript render 'unfavorite_link', post: @post %>');
    

    unfavorite.js.erb

    $('#unfavorite-<%= @post.id %>').replaceWith('<%= escape_javascript render 'favorite_link', post: @post %>');
    

    【讨论】:

    • 太棒了!谢谢AbM!所以我想这里的诀窍是将我的链接也放在单独的部分中。谢谢!
    • 解决方案的工作不需要部分。它们只是用来保持代码干燥。如果出于某种原因您决定更改链接的 html,您只需在一个位置更改它,而不是在 _post.html.erb(un)favorite.js.erb 中更改它
    • 哦,好的,我明白了。感谢您的澄清!
    猜你喜欢
    • 2012-04-22
    • 2016-04-17
    • 2020-04-05
    • 2015-08-26
    • 2016-05-20
    • 2014-11-14
    • 2013-02-15
    • 2012-03-07
    相关资源
    最近更新 更多