1

请解释原因:

User.first.comments.class => Array
User.first.comments.missing_method => undefined method `missing_method' for []:ActiveRecord::Relation

为什么第一行类是 Array 而另一个是 Relation?

4

2 回答 2

1

User.first.comments实际上返回一个 AssociationProxy 对象。调用时您会得到一个数组,User.first.comments.class因为该class方法未定义并被委托给其他地方。

查看Rails 关联方法如何工作?

于 2012-09-19T13:29:06.800 回答
0

因为方法 User.first.comments 存在并且它具有返回值数组,并且对于关系注释不存在missing_method。注释是带有返回值数组的 ActiveRecord::Relation 方法。

于 2012-09-19T12:45:38.037 回答