Tuesday, April 07, 2009

Getting only the columns you want in Rails

A thing that is often missed when your doing a web service or a rails app is selecting only
the columns you need.

A traditional find:

user = User.find :all
render :xml => user.to_xml

Will give you the bloat of the whole user table.
If you only hae a few small columns then thats not so bad,
but I've seen legacy apps that have very large number of columns,
so it makes since then to control this better.

user = User.find(:all, :select = 'email')
render :xml => user

This also will make your resulting xml file alot more managable.
And since bandwidth is not free, it will help you handle more users
for less money.


junior said...

hi glenn..
it's me junior from ruby-forum.com..

in your code..
it's only read column email??

Andy Croll said...

I'd say you were better off redefining the to_xml method within the model to only let out the fields you want.