Change default finder select statement in Rails 3.1

600 Views Asked by At

I'd like to change the default statement that ActiveRecord uses to query a model's table. By default, it queries a table "cables" for example by...

this_cable = Cable.first

results in

SELECT "cables".* FROM "cables" LIMIT 1

I would like to find a way for it to wind up with

SELECT *,askml(wkb_geometry) as kml FROM "cables" LIMIT 1

This way i can call a database function and have that behave like a field on the object.

this_cable.kml
=> "<LineString><coordinates>-73.976879999999994,40.674999999999997 -73.977029999999999,40.674779999999998 -73.977170000000001,40.674770000000002 -73.97775,40.67501</coordinates></LineString>"

This can be accomplished by adding a scope

scope :with_kml, "*,askml(wkb_geometry) as kml"

But I figure that's kind of messy. I would like this "kml" column to always be there, without having to call the "with_kml" scope.

Any ideas?

1

There are 1 best solutions below

0
On BEST ANSWER

Have you tried using default_scope for this, or do you actually want this to be present on all your models?

Something like this might solve your problem:

default_scope select("*, askml(wkb_geometry) as kml")

You might want to change that to cables.* for it to work properly with joins and such, though.