我在我的 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?