mingle
mingle

Reputation: 1617

ActiveRecord::Relation mystery

Please explain why:

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

Why in the first line class is Array and the other is Relation?

Upvotes: 1

Views: 105

Answers (2)

gerky
gerky

Reputation: 6417

User.first.comments actually returns an AssociationProxy object. You're getting an Array when you call User.first.comments.class because the class method is undefined and being delegated elsewhere.

Check out How do rails association methods work?

Upvotes: 1

quatermain
quatermain

Reputation: 1452

Because method User.first.comments exist and it has return value array and missing_method doesn't exist for Relation comments. comments is ActiveRecord::Relation method with return value array.

Upvotes: 0

Related Questions