Reputation: 1599
I was trying to look up how to get just the IDs of Comments, an associated model to Post.
Post has_many Comments
I found through the Rails documentation that you can use the .map method to pluck out just the IDs.
But then, for the heck of it, I tried doing:
p = Post.find(1)
p.comment_ids #[1,2,3]
And it worked! I cannot find this magic-method documented anywhere in the Rails docs. Is this an officially supported way to get has_many relation ids?
Upvotes: 2
Views: 619
Reputation: 118271
If you look at the doco of has-many-association
, you will find the detailed documentation.
collection_singular_ids
:
... these methods, collection is replaced with the symbol passed as the first argument to has_many, and
collection_singular
is replaced with the singularized version of that symbol.
As per the singularize
method -
comments.singularize # => comment
In your case collection_singular
has been replaced with comment
. That's how you got comment_ids
method.
Hope it clears to you.
Upvotes: 1
Reputation: 13663
See the has_many Association Reference:
When you declare a has_many association, the declaring class automatically gains 16 methods related to the association:
Among them are:
collection_singular_ids
collection_singular_ids=ids
Upvotes: 2