【发布时间】:2021-05-23 17:18:53
【问题描述】:
我正在尝试实现向应用添加赞成和反对票,使用按钮或 link_to 远程提交控制器操作,并使用 AJAX 刷新计数部分。
不知何故,赞成或反对总是重定向到成员的路径。当我使用head :no_content 时,我无法提交又名link_to 的表单。拥有一些respond_to do | f |... 也只会呈现操作 URL。
因此,remote: true 有点不工作,因为我有另一个控制器使用 <%= form_for([entry, entry.review], remote: true, :authenticity_token => true) do |f| %>,它工作正常。
我已尝试实现 here、here、here 和 this 教程和 this,但似乎没有任何效果。
我正在使用acts_as_votable。除了 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
【问题讨论】:
-
您在日志中看到什么样的错误消息?另一件事,我很惊讶看到 upvote_entry_path。不应该是 entry_upvote_path 吗?
标签: ruby ruby-on-rails-6