【问题标题】:How to query all records when all method is undefined?未定义所有方法时如何查询所有记录?
【发布时间】:2025-12-25 01:15:16
【问题描述】:

我正在尝试搜索给定 YouTube 视频的 cmets,以查看它是否包含特定字符串。

我使用 Yt gem 的 api 调用运行良好。但是,我很苦恼,因为 .all 和某些 SQL 查询无法正常工作,因为响应集合似乎是延迟加载的。

问题 -- 如何查询 CommentThreads 集合以查看其中的哪些项目包含特定字符串,例如“parts”?

以下是我尝试运行的一些表达式的控制台输出,包括 LIKE 查询:

@video_comments
=> #<Yt::Collections::CommentThreads:0x007fe626f70120>


@video_comments.all
=> NoMethodError: undefined method `all' for #<Yt::Collections::CommentThreads:0x007fe626f70120>


@video_comments.first.text_display
=> "Links for the parts in the description! <br /><br />What color do you want?"


@video_comments.first.text_display.include? "parts"
=> true


@video_comments.where('text_display LIKE ?', "%parts%").first
=> ArgumentError: wrong number of arguments (given 2, expected 0..1)
from /Users/macbook/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/yt-0.28.5/lib/yt/collections/base.rb:37:in `where'

Rails 5.0.1 + ruby​​ 2.3.0p0 + psql (PostgreSQL) 9.6.1

编辑:实际@video_comments 响应http://imgur.com/bjkXWfO

【问题讨论】:

  • 你试过to_a而不是all吗?

标签: mysql sql ruby-on-rails postgresql youtube-api


【解决方案1】:

.all 适用于模型,例如如果您有一个模型 VideoComments,那么 VideoComments.all 将返回所有 cmets。 您的最后一个查询应该可以工作,您只是有一个语法错误,请尝试

    @video_comments.where('text_display iLIKE = ?', "%parts%").first

【讨论】:

  • ArgumentError: wrong number of arguments (given 2, expected 0..1)
【解决方案2】:

首先,@video_cmets 本身不是活动记录。所以,你不能使用@video_comments.all

根据google的commentThreads,响应返回应该是:

{
  "kind": "youtube#commentThread",
  "etag": etag,
  "id": string,
  "snippet": {
    "channelId": string,
    "videoId": string,
    "topLevelComment": comments Resource,
    "canReply": boolean,
    "totalReplyCount": unsigned integer,
    "isPublic": boolean
  },
  "replies": {
    "comments": [
      comments Resource
    ]
  }
}

所以,你的命令应该是:

,而不是使用@video_comments.all
@video_comments.replies.comments 

(如果不成功,请尝试@video_comments["replies"]["comments"]

它应该返回一个 cmets 列表。

好的,下一步您将过滤 cmets 列表以获取有关内容“部分”字的评论。

@video_comments.replies.comments.select{|comment| comment.text_display.include? "parts"}

类似的东西。

详情请参考以下链接:

https://developers.google.com/youtube/v3/docs/commentThreads

【讨论】:

  • @Thanh_Tuong 下面是实际响应:imgur.com/bjkXWfO 所以我尝试以您提到的所有方式访问replies。我也试过.items[items]["items"]snippet等。但他们都说未定义的方法。
  • 嗨@HashRocketSyntax,请尝试这种方式。instance_variable_get("@#{items}")
  • @Thanh_Tuong 谢谢你的帮助。 NameError: undefined local variable or method "items" for #&lt;ScansController:0x007fe633b83c58&gt;
  • 能否请您删除 {} 并尝试使用这个:.instance_variable_get("@items") @HashRocketSyntax
  • 有趣的@video_comments.instance_variable_get("@items") 结果是nil。我在each 上取得了一些成功,但如果可行,这种方式可能会更优雅
【解决方案3】:

我做了类似的事情,最后通过参考:

video_comments['items'][0]['snippet']['data']['textOriginal']

(这将返回实际的评论。然后可以搜索该文本。)
如果没有单引号,或者没有['items'] 之后的 [0](不带引号),它将无法工作。

Items 是一个具有单个元素的数组,其中包括一组数组和散列。如果我尝试搜索整个 Items 数组,它只返回其中嵌套哈希和数组的名称;不是他们的内容。

我发现获取实际内容的唯一方法是直接引用我想要的元素(在这种情况下,['textOriginal'] 中的注释文本。

【讨论】:

    最近更新 更多