As the official site, I defined two models Post and Comment. Comment is nested in Post.
resources :posts do
resources :comments
end
So I can use @post.comments to access all comments a post own. In console:
$ post = Post.new()
$ post.comments.class
> Array
But:
$ post.comments.respond_to?("build")
> true
Why? An array has the method build? How did Rails do? And how can I know other hidden methods of post.comments?
Firstly, your
resourcescalls are in yourroutes.rbfile, which only deals with the URL parsing side of Rails. It’s nothing to do with the associations between your models, which are set up usinghas_manyandbelongs_tocalls in the relevant model files. Ignore the routes file for now as it’s not related to the main part of your question.With respect to associations, you’ll find that
post.commentsis not returning you anArray, it’s actually returning anActiveRecord::Relationobject. ARelationobject is like an array – in fact any method you call on it which isn’t relation-specific (likebuild) is actually passed on to anArrayrepresentation of theRelation‘s contents. So, when you callpost.comments.length, thecommentsassociation object is calling.lengthon its internal array.One of the consequences of this is that calling
post.comments.classactually passes on the.classcall to the Array too!So, what can that
Relationobject actually do? Since the association is set up by thehas_manycall, you can find out in thehas_manydocumentation. Similarly for abelongs_toassociation