我有这两种模式:
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])
并在视图中(haml)我尝试:
= @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?
答案 0 :(得分:1)
@articles
将是一个项目集合,而不仅仅是一个项目(因为您使用了where
方法)。你必须这样做:
@articles.first.articles_type_id
(另请注意,您不必执行.articles_type.id
,因为@articles.first
已具有该类型的ID
答案 1 :(得分:0)
看起来你的逻辑倒退了。
根据您的模型,文章属于article_type。
@articles.first.article_type.id
# OR @articles.first.article_type_id
看起来你错误地将.article_types
多元化应该是.article_type
。
答案 2 :(得分:0)
未定义的方法消息是因为@articles
没有articles_type
方法。您必须访问文章的单个实例才能使用该方法。您可以通过调用@articles.first
或通过迭代集合来实现此目的。
= @articles.first.articles_type.id
是您要使用的行。