【问题标题】:How to implement link_to, AJAX, remote: true, respond_to without rendering new url Rails 6如何实现link_to,AJAX,remote:true,respond_to而不渲染新的url Rails 6
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 我这样做了,并将我的路由更改为post,但我仍然使用remote: true获得路由
  • 您是否也通过在父元素中添加data-turbolinks="false" 来关闭turbo-links?
  • 我刚刚删除了整个turbo-links 功能。我在很多论坛上读到它带来了很多复杂性here 和其他here
  • 我认为这没有必要。我能想到的最后一个办法是尝试从您的页面中删除所有内容,如有必要,返回application.html.erb,并尝试首先让link_to 或button_to 工作
【解决方案2】:

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

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

这在布尔值check-box forms 下会更好地工作,喜欢或不喜欢变量最多只能在两个实例之间交替。因此,您不必编写太多 javascript 来处理伪输出。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 2015-01-04
    • 2015-11-24
    • 1970-01-01
    • 2013-10-12
    • 2013-03-22
    相关资源
    最近更新 更多