使用ajax作为acts_as_votable来避免页面重新加载

时间:2018-09-30 23:16:37

标签: ruby-on-rails ruby ajax

我正在tweets页面上使用acts_as_voteable进行上/下投票,效果很好。但是,当我这样做时,它会重新加载页面,我想避免

<% @tweets.each do |tweet|  %>
  <div class="card">
    <div class="card-description">
      <h4><%= link_to tweet.user.username, user_path(tweet.user) %></h4>
      <p class="tweet-content"><%= tweet.content %></p>
      <p><%= tweet.created_at.strftime("%B %d %Y, %l:%M%P") %></p>
      <%= link_to like_tweet_path(tweet), method: :put do %>
      <p>Upvote <%= tweet.get_upvotes.size %>
      <% end %>
      <%= link_to dislike_tweet_path(tweet), method: :put do %>
      Downvote <%= tweet.get_downvotes.size %></p>
      <% end %>
    </div>
  </div>
<% end %>

class TweetsController < ApplicationController
  before_action :authenticate_user!, :except => [:index]

   def index
    # @tweets = Tweet.all.order("created_at DESC")
    @tweets = Tweet.paginate(page: params[:page], per_page: 7).order('created_at DESC')

    @tweet = Tweet.new
    @user = current_user
  end

  def show
    @tweet = Tweet.find(params[:id])
  end

  def new
    # @tweet = Tweet.new
  end

  def create
    # @user = current_user
    @user = User.find(params[:user_id])
    @tweet = Tweet.new(tweet_params)
    @tweet.user = @user
    if @tweet.save
    redirect_to user_tweets_path
  end
  end

  def edit
    @tweet = Tweet.find(params[:id])
  end

  def update
    @tweet = Tweet.find(params[:id])
    @tweet.update(tweet_params)
    redirect_to tweets_path
  end

  def upvote
  @tweet = Tweet.find(params[:id])
  @tweet.upvote_by current_user
  # redirect_to :tweets
   if request.xhr?
    head :ok
  else
    redirect_to tweets_path
  end
end

def downvote
  @tweet = Tweet.find(params[:id])
  @tweet.downvote_by current_user
  redirect_to :tweets
end

  private
  def tweet_params
    params.require(:tweet).permit(:content)
  end
end

1 个答案:

答案 0 :(得分:0)

您可以在remote: true标记中使用link_to

例如:

您有<%= link_to like_tweet_path(tweet), method: :put do %>

您可以通过这种方式<%= link_to like_tweet_path(tweet), method: :put, remote: true do %>

然后只需使用format.js

处理请求