Friday, November 2, 2007

collection_singular_ids

I was taking a look at the has_and_belongs_to_many and has_many relationships.

Going through the documentation, I found the ability to retrieve the ids of each relationship. Sometimes that can be useful. So I decided to give it a try. Here is the documentation:

collection(force_reload = false) - returns an array of all the associated objects. An empty array is returned if none are found.
...
collection_singular_ids - returns an array of the associated objects ids

I was thinking... "Alright, this looks simple enough". Thinking that collection would allow me to write:

user.cars

So, I thought if I wanted to retrieve the ids, I could do this:

user.cars_singular_ids

Boy was I wrong! I got an "undefined method" error... at this moment in time, I'm thinking "HUH?!?! But the documentation says so..."

After looking around for a bit, I found the solution. Apparently, it's all in the lack of punctuation! What the documentation is really saying is that we should specify the singular form of the collection with _id attached, like so:

user.car_ids

This reminds me of a joke I once heard of which explained the importance of punctuation:

A professor wrote "A woman without her man is nothing" on the chalkboard and told his students to punctuate it. All the males in the classroom wrote "A woman, without her man, is nothing." However, all the females in the classroom wrote "A woman: without her, man is nothing!" Clearly, punctuation is important!

Hope you guys don't have to bump your heads against the wall for as long as I did!

W

No comments: