Rails不会从此操作中返回

时间:2019-07-01 19:47:59

标签: ruby-on-rails

我遇到的问题很简单。基本上,我的视频页面有一个Rails操作。它发出一个HTTP请求并获得一些响应。但是我现在正在尝试添加错误检查。我的问题是,进入if块后将不会离开此操作。它似乎继续尝试在if块之后运行所有代码。这很糟糕,因为如果它进入if块,则意味着我们没有得到200 OK的响应。没有什么可运行的。只是抛出一条错误消息而已!

它正在进入if块(Gyazo link here)。

  def videos
    # get current_user's wistia_project_id & authorization token
    @current_user = current_user
    project_id = @current_user.wistia_project_id
    auth_token = "blah"
    request = "https://api.wistia.com/v1/projects/#{project_id}.json?api_password=#{auth_token}"

    @response = HTTP.get(request)

    puts "BEFORE"

    # handle errors (4xx & 5xx)
    # catches client errors and server errors
    # should print out and then LEAVE this entire action. (return)
    if @response.status.client_error? || @response.status.server_error?
      puts "INSIDE"
      render text: "Sorry, error"
      return
    end

    @response = HTTP.get(request).body
    # get embed code for each video using the hashed_id, put in list
    # BUT!!! for some reason it gets here and there's an error 
    # because there is nothing in the response (errors) 
    @video_iframe_urls = JSON.parse(@response)['medias'].map do |p|
      "https://fast.wistia.com/embed/iframe/#{p["hashed_id"]}?version=v1&controlsVisibleOnLoad=true&playerColor=aae3d8"
    end
  end

1 个答案:

答案 0 :(得分:1)

render text: "Sorry, error"

将此行更改为普通

render plain: "Sorry, error"

问题不是

  

进入if块后,它将不保留此操作。

因为渲染不支持文本选项。您的代码实际上是

    if @response.status.client_error? || @response.status.server_error?
      puts "INSIDE"
      render
      return
    end

render方法按默认操作名称渲染模板名称