ruby - Namespaced model in Rails generating NameError: uninitialized constant -


i have folder structure this:

app/   models/     bar/       foo.rb       connection.rb     foo.rb 

connection.rb "abstract class" connecting database, so:

class bar::connection < activerecord::base   self.abstract_class = true   establish_connection "outsidedb_#{rails.env}" end 

bar/foo.rb accessing foos table outsidedb, so:

class bar::foo < bar::connection end 

and foo.rb accessing foos table app's db, so:

class foo < activerecord::base end 

from rails console if foo.first or bar::foo.first things behave expect in first entry foos table of app db , external db, respectively.

however, if try access foo within bar/foo.rb following:

class bar::foo < bar::connection   def self.test       bar::foo.first #=> works       foo.first      #=> nameerror: uninitialized constant bar::foo::foo   end    def self.other_test     foo.parent                    #=> object     foo.superclass                #=> activerecord::base     object::foo.first             #=> works     activerecord::base::foo.first #=> works, "warning: toplevel constant                                    #   foo referenced activerecord::base::foo   end end 

i can things working, i'm looking sounder understanding of what's going on. i'm assuming i'm missing between ruby's constant/class evaluation , rail's builtin auto-loading...

  1. what .parent returning (not 'parent' class)?
  2. why error in .test, don't in rails console?
  3. why object::foo seem work? right thing do?
  4. why activerecord::base::foo work, warning?
  5. there more rails way i've done without renaming 1 of foo.rb classes?

i'm on rails '3.2.13' , ruby 1.9.3-p194, know!

your problem can fixed with

::foo.first 

here ::foo indicating class foo in top namespace.

you problem comes fact, there foo class in namespace (bar) working in. should explicit.

as question why object::foo works (with warnings), it's (less) known behaviour of name lookup in ruby. please see this article more details.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -