Quick Query

December 5th, 2007 -

I was writing some documentation for Rails last night (for Array Conversions), and ran across a handy little method I didn’t know about, which is quite useful.

Say you have a person who has many jobs posted and each one of those jobs have many applicants. You want to see all applicants for all jobs, for a specific person. Here is a really quick example of how to do that:

person = Person.find :first

Applicant.find_all_by_job_id(person.jobs.to_formatted_s(:db))

or, as Chris stated(in the comments), you can just do Applicant.find_all_by_job_id(person.jobs)

That’s that.

Tags: rails

 

Comments

Chris

December 5th, 2007

First, you can just use to_s(:db)—the to_formatted_s is the name of the alias’d method.

Second, this is implicit: Applicant.find(person.jobs) will do the same thing.

And yes, awesome feature!

Robert

December 5th, 2007

@Chris, yeah, I knew the to_s(:db) (not sure why I didn’t state that as well), but didn’t even think about Applicant.find(person.jobs) working. Nice

Matt Jones

December 5th, 2007

Couldn’t you also just declare has_many :through on Person? Then you would be able to use person.applicants, with all the usual query caching, etc.

Robert

December 5th, 2007

@Matt: yeah, most definitely, but then where would this blogs be? ;) I just liked this little nugget and used person, job, applicant to drive the point.

nicolash

December 12th, 2007

sorry – i don’t get it… person.jobs.to_formatted_s(:db) gives you an array of the job-ids for the person right? then you do an ordinary find on Applicant… right? ... but this would find you applicants that happen to have the same ids like the jobs of the person….

what do i get wrong here?

Robert

December 12th, 2007

Nicolash: it was a mistype and has been corrected.

 

Commenting has been turned off.