-1

我在我的 Rails 应用程序中使用 gem“acts_as_votable”,以便用户可以对帖子进行投票。一切正常。

在此处输入图像描述

但是,如果您对帖子投赞成票或反对票,则整个页面都会刷新。我想通过实现 Ajax 来改变这一点,这应该是不刷新整个页面的理想解决方案。这是我到目前为止所拥有的:

路线.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

post_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

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 %>

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

4

1 回答 1

1

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

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

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

<%= link_to "Approve", toggle_approve_post_path(post), :remote => true %>

在我的路线中,我的帖子路线(routes.rb)中有一条自定义路线:

resources :posts do
    get 'toggle_approve',   :on => :member
  end
于 2017-01-09T01:45:55.977 回答