微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在不渲染新 url 的情况下实现 link_to、AJAX、remote: true、respond_to Rails 6

如何解决如何在不渲染新 url 的情况下实现 link_to、AJAX、remote: true、respond_to Rails 6

我正在尝试向应用添加赞成票和反对票,使用按钮或 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| %> 的控制器并且它工作得很好。

我曾尝试实施 herehereherethis 教程和 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),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

解决方法

不确定您的 a 标签是否在其他元素内,但您可能需要考虑使用 button_to 而不是 link_to

,

到目前为止,临时解决方案(可能不推荐,但仍可用于编程实践)是在特定条件下隐藏和取消隐藏某些元素。

根据用户交互(例如 onClick),在更新类似于控制器更新的值时取消隐藏和隐藏元素。只需模拟刷新并更新它们指向的表单路径/控制器操作。

这对于布尔值 check-box forms、喜欢或不喜欢的大多数情况下效果更好,其中变量最多只能在两个实例之间交替。因此,您不必编写太多 javascript 来处理伪输出。

不过,我相信还有更好的方法,例如 WebSocketsAction Cable。这可能有点矫枉过正,但最接近实时更新。 respond_to 似乎不起作用

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。