Rails 4:发出POST请求后重定向不起作用

时间:2015-03-02 08:30:25

标签: ruby-on-rails

所以我们有两个模型,文章和喜欢。文章has_many :likes,类似belongs_to :userbelongs_to :article。资源嵌套如下:

resources :articles do
  resources :likes
end

在我们的视图中,我们有一个逻辑,它呈现一个“喜欢”或“不像”按钮,如下所示:

<% unless signed_in? and current_user.likes? @article %>
  <%= link_to "Like this article!", article_likes_path(@article), method: :post, remote: true %>
<% else %>
  <%= link_to "Unlike this article!", article_like_path(@article, current_user.article_like(@article)), method: :delete, remote: true %>
<% end %>

这是我们的LikesController:

class LikesController < ApplicationController
  before_action :set_article
  before_action :set_like, only: [:destroy]
  before_action :authenticate_user!

  after_action :redirect_to_article, only: [:create, :destroy]

  respond_to :html

  def create
    like = Like.new
    current_user.likes << like
    @article.likes << like
    redirect_to @article
  end

  def destroy
    @like.destroy
    redirect_to @article
  end

  private
    def set_article
      @article = Article.find(params[:article_id])
    end

    def set_like
      @like = Like.find(params[:id])
    end

    def like_params
      params[:like]
    end

    def redirect_to_article
      redirect_to @article
    end
end

在视图中,喜欢计数使用:

呈现

<%= @article.likes.size %>

问题,在我们点击“喜欢”或“不像”之后,类似(或不同)通过后端,但我们必须手动刷新页面以查看类似计数刷新。换句话说,LikesController中对redirect_to @article的两次调用实际上并不刷新页面。

有什么想法吗?感谢。

1 个答案:

答案 0 :(得分:4)

您的按钮正在使用remote: true告诉Rails使用AJAX,但您的控制器设置为仅响应HTML。从您的问题来看,听起来您在刷新页面时感觉很酷,所以只需从按钮中删除remote: true即可。