我有两个模型:
class Article < ActiveRecord::Base
belongs_to :articles_type
end
class ArticlesType < ActiveRecord::Base
has_many :articles
end
在控制器中我写道:
@articles = Article.where(article_type_id: params[:id])
在视野(哈姆尔)中,我尝试:
= @articles.articles_type.id
= @articles.articles_types.id
= @articles.first.articles_type.id
= @articles.first.articles_types.id
我如何显示此 articles_type.id,但仅适用于第一行?
现在我得到
undefined method `articles_type'
但是为什么呢?我做错了什么?如何显示嵌套的模型 ID?
@articles
将是项的集合,而不仅仅是单个项(因为您使用了where
方法)。您将必须执行以下操作:
@articles.first.articles_type_id
(另请注意,您不必执行.articles_type.id
,因为@articles.first
已经具有该类型的 ID)
未定义的方法消息是因为@articles
没有articles_type
方法。您必须访问文章的单个实例才能使用该方法。可以通过调用@articles.first
或迭代集合来执行此操作。
= @articles.first.articles_type.id
是要使用的行。
看起来你的逻辑倒退了。
根据您的模型,文章属于article_type。
@articles.first.article_type.id
# OR @articles.first.article_type_id
只是看起来你在应该.article_type
的时候错误地复数了.article_types
.