Thursday, October 01, 2009

Rails Trick: Access an ActiveRecord field in a loop in a view

I came up with a little trick that I want to share, even though I'm sure there are better ways of doing this (perhaps someone will suggest them!)

OK, picture this: We have over half a dozen different types of workers -- Writers, Sr. Editors, Editors, etc. -- and we're going to pay them. So, in the database we have things like writer_payment, sr_editor_payment and editor_payment.

In the edit view, we have something like this (actually, there are many more cells, but I've omitted them for clarity):



And, I fully expect that we will be adding many more workers, so we can look forward to much cutting and pasting.

Well, I wanted to come up with a way of declaring an array, iterating through it and creating each row automagically.

My first thought was this:



But this doesn't work at all. The ActiveRecord attribute can't be built dynamically with string interpolation in the view. Similar efforts failed miserably.

But then I took at look at the ActiveRecord::Base class and noticed the attributes method. This got me a-thinkin' and here's what I came up with. Get the attributes from the ActiveRecord. Build a string with the array value and the "_payment", use straight array access to get the payment value



And, Holy Smakeral -- it works!

No comments:

Post a Comment