我正在运行一个调用Simplecasts API来显示我的播客剧集的rails应用程序。我按照教程使用Faraday来设置API服务。我的问题是如何在我的索引页上只显示已发布的剧集?通常情况下,我会在索引页上添加一个 .where(:status => "live")
在我的控制器中,IE @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
看起来像集合只是一个哈希数组,所以rails ActivrRelations方法又名.where不支持。然而,它是一个数组,所以你可以只过滤这个数组。
published_episodes = collection.filter { --