【问题标题】:Why the object returned is Enumerable?为什么返回的对象是可枚举的?
【发布时间】:2026-02-10 13:45:01
【问题描述】:

我不明白为什么我得到一个 Enumerable 而不是一个对象。当我运行这段代码时:

 - @posts.each do |post|
    = Comment.find(id: post.id).title

我遇到了这个错误:

#Enumerator 的未定义方法 `title': Comment:find({:id=>1})>

如果我签入控制台,我还会得到 Enumerator :

[2] pry(#<Sinatra::Application>)> Comment.find 1
 => #<Enumerator: ...>

我只想拥有像#<Comment @id=1 @content="great" @post_id=1> 这样的对象

我正在使用 Sinatra 和 Datamapper。

【问题讨论】:

  • 您确定您正在使用 Datamapper 吗?我在问,因为 Datamapper 没有在模型上定义 find 方法。然而,ActiveRecord 和 Sequel 一样。
  • 这是我第一次使用datamapper。我认为调用对象的方法是相同的,这可能是实际问题!
  • 查看datamapper.org/docs/find.html 获取一些文档。

标签: ruby object sinatra


【解决方案1】:

您要查找的查询是:

Comment.first(id: post.id).title

这是一个简短的版本:

Comment.all(id: post.id).first.title

Datamapper 中没有find(据我所知)。您实际看到的是 Ruby 的 Enumerable#find:http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-find 的结果,它必须是 Datamapper 对象的一部分。

【讨论】: