1

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?

slaphappy
  • 6,894
  • 3
  • 34
  • 59
mingle
  • 1,567
  • 1
  • 16
  • 19

2 Answers2

1

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?

Community
  • 1
  • 1
gerky
  • 6,267
  • 11
  • 55
  • 82
  • 1
    Looks like your're right http://apidock.com/rails/ActiveRecord/Associations/AssociationProxy – mingle Sep 19 '12 at 14:54
0

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.

quatermain
  • 1,442
  • 2
  • 18
  • 33
  • You say that method comments returns Array so why when I call some method on Array it goes to Relation? – mingle Sep 19 '12 at 12:53
  • Because comments is relation class, if you call it alone "User.first.comments" it run method which return array, but if you call array's method on comments, comments is Array class. – quatermain Sep 19 '12 at 13:03