Jan 23 2011
∞
has_many through issue with postgres and namespaced models
Let’s say you have the following models:
class Carton < ActiveRecord::Base has_many :carton_eggs, :class_name => "Carton::Egg" has_many :eggs, :through => :carton_eggs, :order => "egg_order" end class Carton::Egg < ActiveRecord::Base belongs_to :carton belongs_to :egg end class Egg < ActiveRecord::Base endWhen running the following:
carton.eggsYou’ll likely get an error like this:
ERROR: table name "carton_eggs" specified more than once
STATEMENT: SELECT "carton_eggs".* FROM "carton_eggs" INNER JOIN "carton_eggs" ON "carton_eggs".id = "carton_eggs".egg_id WHERE (("carton_eggs".carton_id = 157)) ORDER BY display_order
The first table should definitely be “eggs”, not “carton_eggs”, but for some reason it’s not.
I didn’t dig in much into why the sql was incorrect here — looking through a debugger the activerecord association proxy object looked largely correct, but after 30 minutes I just yanked the namespacing — used CartonEgg instead of Carton::Egg — and boom, everything worked.
A bit of a bummer, since I typically like the neater organization of namespaced models (this particular model was in a carton/ sub dir, with the filename of egg.rb). I guess I’ll revisit this later when I have more than 5 models in my app. Apparently many folks aren’t fans of namespacing in models (http://m.onkey.org/namespaced-models), and I’ve definitely hit namespace bugs before, so maybe in this project I’ll avoid them and see how far I can get.