Ruby on rails 用于在帖子上投票的Ajax(停止页面刷新)

Ruby on rails 用于在帖子上投票的Ajax(停止页面刷新),ruby-on-rails,ruby,ajax,acts-as-votable,Ruby On Rails,Ruby,Ajax,Acts As Votable,我在Rails应用程序中使用gem“acts_as_votable”,这样用户就可以对帖子进行投票。一切都很好 但如果你对一篇文章投上或下的票,整个页面都会刷新。我想通过实现Ajax来改变这一点,Ajax应该是不刷新整个页面的理想解决方案。这就是我到目前为止所做的: routes.rb resources :posts do member do put "like", to: "posts#upvote" put "dislike", to: "posts#downvote" end

我在Rails应用程序中使用gem“acts_as_votable”,这样用户就可以对帖子进行投票。一切都很好

但如果你对一篇文章投上或下的票,整个页面都会刷新。我想通过实现Ajax来改变这一点,Ajax应该是不刷新整个页面的理想解决方案。这就是我到目前为止所做的:

routes.rb

resources :posts do 
member do
  put "like", to: "posts#upvote"
  put "dislike", to: "posts#downvote"
end
end
post.rb

class Post < ActiveRecord::Base

belongs_to :user
acts_as_votable

validates :user_id, presence: true
validates :content, presence: true, length: { maximum: 320,
too_long: "%{count} characters is the maximum allowed" }
default_scope -> { order(created_at: :desc) }

end
class Post{顺序(在::desc创建)}
结束
posts\u controller.rb

class PostsController < ApplicationController

def index
..stuff here..
end

def new 
..stuff here..
end

def create
..stuff here..
end

def destroy
..stuff here..
end

def upvote
  @post = Post.find(params[:id])
  @post.upvote_by current_user
  redirect_to :back
end  

def downvote
  @post = Post.find(params[:id])
  @post.downvote_by current_user
  redirect_to :back
end

private
def post_params # allows certain data to be passed via form.
    params.require(:post).permit(:user_id, :content)
end

end
  def toggle_approve
    @a = Post.find(params[:id])
    @a.toggle!(:visible)
    render :nothing => true      # I don't my controller to redirect or render
  end
class PostsController
explore.html.erb

<% if @posts.each do |p| %>
<div class="panel-body">
  <p class="post-content"><%= auto_link(p.content, :html => { :target => '_blank' }) %></p>

  <%=link_to like_post_path(p), method: :put, class: 'btn btn-default btn-sm' do %>
    <span class="glyphicon glyphicon-chevron-up"></span> like <%=p.get_upvotes.size%></td>
  <% end %>

 <%=link_to dislike_post_path(p), method: :put, class: 'btn btn-default btn-sm' do %>
   <span class="glyphicon glyphicon-chevron-down"></span> dislike <%=p.get_downvotes.size%></td>
 <%end%>

</div>
<% end %>

{:target=>'\u blank'})%>

喜欢 不喜欢

如何将我所拥有的转换为Ajax?

我的方法是向我的控制器发送一个Ajax get请求,并像您一样在那里处理它: (post_controller.rb)

在我看来,我创建了这样一个Ajax链接(_post.erb):


我投票将这个问题作为离题题来结束,因为它没有显示出实际解决问题的努力,而只是代码钓鱼。
<%= link_to "Approve", toggle_approve_post_path(post), :remote => true %>
resources :posts do
    get 'toggle_approve',   :on => :member
  end