【问题标题】:Rails display only published episodes from Simplecast apiRails 仅显示来自 Simplecast api 的已发布剧集
【发布时间】:2020-04-23 03:42:05
【问题描述】:

我正在运行一个调用 Simplecasts API 的 Rails 应用程序来显示我的播客片段。我按照教程使用 Faraday 设置 API 服务。我的问题是如何只在我的索引页面上显示已发布的剧集?通常,我会在我的控制器中添加一个.where(:status => "live"),即@podcasts = Episodes.where(:status => "published"),但这似乎不起作用。

Simplecast 的播客 API 返回一个 collection,其中包含所有可用的剧集,每个剧集都有一个 status 节点。

任何帮助都将不胜感激,因为我是在 Rails 中使用外部 API 的新手

示例 API 响应

"collection": [
    {
        "updated_at": "2020-03-25T17:57:00.000000-04:00",
        "type": "full",
        "token": "lgjOmFwr",
        "title": "Test",
        "status": "draft",

Episode.rb

module Simplecast
  class Episodes < Base
    attr_accessor :count,
                  :slug,
                  :title,
                  :status

    MAX_LIMIT = 10

    def self.episodes(query = {})
      response = Request.where('/podcasts/3fec0e0e-faaa-461f-850d-14d0b3787980/episodes', query.merge({ number: MAX_LIMIT }))
      episodes = response.fetch('collection', []).map { |episode| Episode.new(episode) }
      [ episodes, response[:errors] ]
    end

    def self.find(id)
      response = Request.get("episodes/#{id}")
      Episode.new(response)
    end

    def initialize(args = {})
      super(args)
      self.collection = parse_collection(args)
    end

    def parse_collection(args = {})
      args.fetch("collection", []).map { |episode| Episode.new(episode) }
    end
  end
end

控制器

class PodcastsController < ApplicationController
  layout "default"


  def index

    @podcasts, @errors = Simplecast::Episodes.episodes(query)

    @podcast, @errors = Simplecast::Podcast.podcast(query)

    render 'index'
  end

  # GET /posts/1
  # GET /posts/1.json
  def show
    @podcast = Simplecast::Episodes.find(params[:id])
    respond_to do |format|
      format.html
      format.js
    end
  end

  private
    def query
      params.permit(:query, {}).to_h
    end
end

【问题讨论】:

  • where 通常适用于 ActiveRecord 类/关系对象。您是否将剧集存储在数据库中?

标签: ruby-on-rails api ruby-on-rails-5 faraday


【解决方案1】:

看起来collection 只是一个哈希数组,所以rails ActivrRelations 方法又名.where 不受支持。但是它是一个数组,所以你可以过滤这个数组:

published_episodes = collection.filter { |episode|剧集[:status] == “已发布” }

还可以查看他们的 API - 可能确实支持可选过滤参数,因此您首先只能获得已发布的剧集。

顺便说一句:第二个想法是将外部 API 请求数据保存在您自己的数据库中,然后使用标准 .where 流获取需要的情节。

【讨论】:

  • 谢谢。有没有办法将它与此结合以仅映射已发布的剧集? episodes = response.fetch('collection', []).map { |episode| Episode.new(episode) }
  • 你敢打赌,它是 Ruby:ruby-doc.org/core-2.7.0/Enumerable.html#method-i-filter_map。另外,我将这两个操作以显式方法分开是一个不错的决定——从 api 获取并映射到您的模型上。单一责任 - S 代表 SOLID
猜你喜欢
  • 1970-01-01
  • 2019-05-14
  • 1970-01-01
  • 2014-02-16
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 2022-12-17
  • 1970-01-01
相关资源
最近更新 更多