我正在使用gem" acts_as_votable"在我的Rails应用程序中,以便用户可以对帖子进行投票。一切正常。
但是如果你对一篇文章进行投票或者投票,那么整个页面就会刷新。我想通过实现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
posts_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?
答案 0 :(得分:1)
我的方法是向我的控制器发送一个ajax get请求并像你一样处理它: (post_controller.rb)
@foreach (var item in (List<string>)TempData["tableList"])
{
@Html.Raw(item.ToString().Replace(";", "</td></tr><tr><td>"))
}
在我看来,我创建了一个像这样的Ajax链接(_post.erb):
def toggle_approve
@a = Post.find(params[:id])
@a.toggle!(:visible)
render :nothing => true # I don't my controller to redirect or render
end
在我的路线中,我的帖子路线(routes.rb)中有自定义路线:
<%= link_to "Approve", toggle_approve_post_path(post), :remote => true %>