Question

I have a new rails app which needs to access data from a legacy table called "Doo_dad", with an autoincrementing primary key called "id", and a string field called "name".

So I created a new model file called app/models/doodad.rb which looks like this:

class Doodad < ActiveRecord::Base
   set_table_name "Doo_dad"
end

When I loaded Rails console, I could reach my Rails-generated models, but I could not see the class

> rails console
irb> Doodad.class
NameError: uninitialized constant Doodad
(from (irb):1: in `evaluate`

Class Doodad in app/models/doodad.rb was not getting loaded. This code is good, because when I did the following:

> rails console
irb> class Doodad < ActiveRecord::Base
irb> set_table_name "Doo_dad"
irb> end
irb> Doodad.class
 => OK
irb> d=Doodad.new
irb> d.name="Uno"
irb> d.save
 => OK no errors

i.e. When I monkey-patched in the contents of app/models/doodad.rb, everything was fine, and the Doodad called "Uno" was saved into the database.

How can I get Rails to load up my model classes which hook up to legacy tables?

Was it helpful?

Solution

D'oh! I had the class in app/models/doodads.rb. Once I renamed it to app/models/doodad.rb, everything was fine.

I guess that the convention of one model class per file with the Rails model file naming convention (filename=classname.underscore+".rb") is an absolute "must" to get this working.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top