【问题标题】:Rails - ajax not responding when respond_to wrapped in if statementRails - 当respond_to包含在if语句中时ajax没有响应
【发布时间】:2016-09-07 01:55:46
【问题描述】:

背景:我正在使用acts_as_votable gem 在Resource 模型上记录喜欢。我正在努力拆分点赞按钮的行为,以适应 (a) 已登录用户和 (b) 未登录用户。

资源控制器中的之前/之后操作

before_action :set_resource, only: [:show, :edit, :update, :destroy]
before_action :save_original_path, only: [:like]
before_action :require_signin!, only: [:like]
after_action :clear_original_path, only: [:like]

如果用户没有登录,并且他们点击了点赞按钮,我会存储他们的原始路径 --> 强制他们登录 --> 返回到他们的原始路径(喜欢资源) --> 并重定向他们返回资源索引。

如果用户已登录,则简单地使用ajax来记录投票并刷新页面。

like resources_controller.rb 中的操作

def like
  @resource = Resource.find(params[:id])
  @resource.liked_by current_user
  if session[:return_to] != nil
    redirect_to resources_path
  else
    respond_to do |format|
      format.html
      format.js
    end
  end
end

上面类似操作中的 if 语句发生了一些奇怪的事情。 redirect_to resources_path 流程非常适合未登录的用户。但是,respond_to ajax 调用不会刷新页面。

如果我将 respond_to 调用移出 if 语句并删除 if 语句,那么它工作得很好。

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby ajax acts-as-votable


    【解决方案1】:

    搞定了。不出所料,我把它弄得太复杂了。这有效:

    def like
      @resource = Resource.find(params[:id])
      @resource.liked_by current_user
      respond_to do |format|
        if session[:return_to] != nil
          format.html { redirect_to(resources_path) }
        end
        format.html
        format.js
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      • 1970-01-01
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      相关资源
      最近更新 更多