试图找出如何让 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");
现在我已经部分工作了。我有两个问题。
- 每个页面包含多个帖子。我如何告诉 format.js.erb 文件定位该特定帖子的最爱按钮。现在,无论我在页面上单击什么位置,jQuery 都只会更改第一个帖子按钮。我尝试将 link_to id 设置为 favorite<%= post.id %> ,然后在 format.js 文件中使用 favorite<%= post.id %> 但这不起作用。
- 我想更改 format.js 文件以将实际按钮放入 div 中,而不仅仅是更改其文本。因此,用户可以切换最喜欢的和不最喜欢的,而无需刷新页面。我尝试将 link_to 按钮放入 .html("") 部分,但这不起作用。我不知道如何使用ajax提交post请求。
谢谢您的帮助!如果您需要更多代码或者我不清楚某些内容,请告诉我。
最佳答案
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
来替换整个链接,而不仅仅是其内部 HTML,而不是仅使用 AJAX 设置 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 %>');
关于javascript - Acts_As_Votable Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34011279/