Rails 方法无法识别

Rails method not recognised

我正在阅读一本关于 Rails 的书,该书展示了如何构建博客应用程序。我刚刚添加了向博客帖子添加评论的功能,Rails 抛出了一个我无法修复的错误。

根据 rails,未定义以下行中的方法 "published":

errors.add(:article_id, "is not published yet") if article && !article.published?

通过追踪,我发现我的文章模型包含该行

scope :published, lambda { where("articles.published_at IS NOT NULL") }

作为一个 Rails 菜鸟,我不完全确定 "scope" 在这种情况下是什么意思,但我猜测它定义了一个方法,可以通过调用 article.published?。我说得对吗?

从我在网上阅读的内容来看,这个问题似乎与我正在为 Rails 4.0 编写的书有关,而我正在使用 Rails 4.2 .0。我需要在此行中更改什么才能使其与 Rails 4.2.0 一起使用?

该错误与您正在使用的 Rails 版本无关,您只是在错误的对象上调用了方法。

首先,请注意 publishedpublished? 之间存在差异。第二个有问号。

scope 方法定义了一个 class 方法来过滤结果,因此它在 class 上可用。例如

@articles = Article.published.where()...

不过,您正在使用 实例 ,并且可能想要定义一个实例方法,例如:

def published?
  published_at.present?
end