【问题标题】:acts_as_votable ajax not updating the data until I refresh the whole page在我刷新整个页面之前,acts_as_votable ajax 不会更新数据
【发布时间】:2020-06-06 14:38:33
【问题描述】:

你好,我是 Rails 的新手

实际上投票工作正常,但在我刷新整个页面之前它不会更新数据

这是我投票时的错误

这是我的代码

routes.rb

resources :posts do
 match :vote, via: [:post, :delete], on: :member
end

controller.rb

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy, :vote]
  respond_to :js, :html, :json
  def vote
   @post = Post.find(params[:id])
   if request.post?
       @post.upvote_from current_user
   elsif request.delete?
       @post.downvote_from current_user
   end
   respond_to do |format|
      format.html { redirect_to :back }
      format.js
   end
  end

投票.js.erb

$("<%=j @post.id %>").html("<%=j render partial: "posts/vote", locals: { post: @post } %>");

_vote.html.erb

<% voted   = current_user.voted_for? post %>
<% styling = voted ? "" : "un" %>
<% arrow   = voted ? "up" : "down" %>
 <% method  = voted ? :delete : :post %>

 <%= link_to vote_post_path(post), method: method, remote: true, class: '# 
{styling}like_post', id: post.id do %>
    <button type="button" class="btn btn-info" aria-label="Left Align">
           <i class="fa fa-arrow-<%= arrow %>"></i>
        <span class="badge vote_count"><%= post.get_upvotes.size %></span>
     </button>
 <% end %>

show.html.erb

<%= render partial: "vote", locals: { post: @post } %>

应用程序.js

//= require rails-ujs
//= require turbolinks
//= require_tree .
//= require jquery3
//= require popper
//= require bootstrap-sprockets

【问题讨论】:

    标签: ruby-on-rails ajax gsub voting


    【解决方案1】:
    $("<%= @post.id %>").html("<%=j render partial: "posts/vote", locals: { post: @post } %>");
    

    如果不是脚本/文本,则不需要转义。假设帖子的 id 为 5,因此出现错误

    undefined method `gsub' for 5:Integer
    

    【讨论】:

    • 错误没有出现,但它也没有更新数据......
    • 你能在网络标签上检查一下,看看会发生什么,检查它是否有相同的响应。
    • 您正在用整个部分替换 link_to 中的内容。您应该使用 id 为 post.id 的元素将内容部分括起来。那么它应该可以工作。我没有修改答案,因为问题是关于 ajax 返回 500 状态。如果您更新问题,我会尽力回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 2020-03-01
    • 2021-01-04
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    相关资源
    最近更新 更多