如何在不渲染新 url 的情况下实现 link_to、AJAX、remote: true、respond_to Rails 6 [英] How to implement link_to, AJAX, remote: true, respond_to without rendering new url Rails 6
问题描述
我正在尝试向应用添加赞成票和反对票,使用按钮或 link_to 远程提交控制器操作,并使用 AJAX 刷新计数部分.
I'm trying to implement adding upvote and downvotes to an app, submit the controller actions remotely using a button or link_to, and refresh a count section with AJAX.
不知何故,赞成或反对总是重定向到成员的路径.当我使用 head :no_content
时,我无法提交表单又名 link_to
.有一些respond_to do |f |...
也只是呈现动作 URL.
Somehow upvoting or downvoting always redirects to a path of a member. When I use head :no_content
, I can't submit the form aka link_to
. Having some respond_to do | f |...
also just renders the action URL.
因此,remote: true
有点不工作,因为我有另一个控制器使用 <%= form_for([entry, entry.review], remote: true, :authenticity_token=> 真) 做 |f|%>
并且它完美运行.
Thus, remote: true
is kind of not working, as I have another controller using <%= form_for([entry, entry.review], remote: true, :authenticity_token => true) do |f| %>
and it works perfectly.
我已尝试在此处实施, 这里、此处和
I have tried implementing here, here, here, and this tutorial and this but nothing seems to work.
我正在使用 acts_as_votable.除了 AJAX 的路由功能外,一切正常
I'm using the acts_as_votable. Everything works except the routing functionality with AJAX
# routes.rb
resources :entries do
member do
post 'upvote'
post 'unupvote'
post 'downvote'
post 'undownvote'
end
end
# entries_controller.rb
def upvote
@entry.liked_by current_user
end
def unupvote
@entry.unliked_by current_user
end
def downvote
@entry.disliked_by current_user
end
def undownvote
@entry.undisliked_by current_user
end
# entries/index.html.erb
...
<%= button_to upvote_entry_path(entry.id), remote: true,
class: "btn",
id: "upvote-button-#{ entry.id }" do %>
<i class="bi bi-hand-thumbs-up" style="color: #ababab;" id="upvote-<%= entry.id %>"></i>
<small id="upcount-<%= entry.id %>" >
<%= render 'entries/upvote', entry: entry %>
</small>
<% end %>
...
# entries/_upvote.html.erb
<%= entry.get_upvotes.size %>
# entries/upvote.js.erb
$('#upvote-<%= entry.id %>').className('bi bi-hand-thumbs-up-fill');
$('#upvote-<%= entry.id %>').attr('href', '/entries/<%= entry.id %>/unupvote');
$('#upcount-<%= entry.id %>').html('<%=j render 'entries/upvote', entry: entry %>');
编辑,我已将我的link_to
更改为button_to
,将路由更改为post
Edit, I have changed my link_to
to button_to
, changed the routes to post
推荐答案
不确定您的 a
标签是否在其他元素内,但您可能需要考虑使用 button_to
而不是 link_to
.
Not sure if your a
tag is inside other elements but you might want to consider using a button_to
instead of a link_to
.
这篇关于如何在不渲染新 url 的情况下实现 link_to、AJAX、remote: true、respond_to Rails 6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!