我如何使其不刷新页面?相反,它只会更新计数数字吗?任何帮助,将不胜感激!

故事 Controller :

def like
  like = Like.create(like: params[:like], user: current_user, story: @story)
  if like.valid?
    flash[:success] = "Your selection was succesful"
    redirect_to :back
  else
    flash[:danger] = "You can only like/dislike a story once"
    redirect_to :back
  end
end

index.html.erb:
<div class="pull-right">
    <%= link_to like_story_path(story, like: true), :method => :put, :remote => true  do %>
       <i class="glyphicon glyphicon-thumbs-up"></i><%= story.thumbs_up_total %>
    <% end %>

    <%= link_to like_story_path(story, like: false), :method => :put, :remote => true  do %>
       <i class="glyphicon glyphicon-thumbs-down"></i><%= story.thumbs_down_total %>
    <% end %>
</div>

Story.rb模型:
def thumbs_up_total
  self.likes.where(like: true).size
end

def thumbs_down_total
  self.likes.where(like: false).size
end

最佳答案

Controller 应按照Working with JavaScript in Rails中的说明对respond_to“格式”进行js编码。

代替redirect_to :back,以有意义的状态码响应,例如201(成功)(创建新资源时)或400(错误请求)。

参见RFC 2616, section 10 - Status Code Definitions

然后,在您的JS中处理ajax:success事件。 Working with JavaScript in Rails中也对此进行了描述。

关于javascript - 在Rails中将Ajax/JS包含到我的投票系统中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31643320/

10-12 13:20