Wednesday, March 14, 2007

ActiveRecord magic

Or so Josh Susser puts it. I think it is. It's dynamic finding. I had no idea this was possible until a few days ago when i wrote some moderately-ugly looking method like:



def find_or_create_order
unless @order = Order.find(params[:blah])
@order = Order.create!(params[:blah])
end
end

Then one of the geniuses (since I am working with multiple geniuses) I am working with right now came over and said "You can just use Order.find_or_create_by_blah(params[:blah])." I tried it out, and to my amazement (and I am easily amazed, and amused) it worked! I could try to explain it, but I think Josh Susser has a far greater understanding of how it works, so just go read his post if you're interested.


I did however do some playing, and found some really cool things you can do with these finders. Let's say you have an ActiveRecord model named Order. Let's also say that Order has 7 attributes on it, each labeled "1" through "7". You can write a massive line of code to find or create an Order as follows:



Order.find_or_create_by_1_and_2_and_3_and_4_and_5_and_6
_and_7("1", "2", "3", "4", "5", "6", "7")

The possibilities are endless!!!! Or so I imagine. One easy way to find out is to make an ActiveRecord model with 50 attributes and try to find_or_create one using the above method :-) I'm sure there are more sophisticated ways of using this, but just think of the shock value when you show this to a competent programmer. Their jaw will drop, and they'll say something like "You're smoking crack, man!"