9

I have code like this.

class User < ActiveRecord::Base
end

module Foo
  class User
  end
end

module Foo
  class DoesSomethingWithActiveRecordUser
    def initialize user_id
      User.find(user_id)
    end
  end
end

If I call Foo::DoesSomethingWithActiveRecordUser.new(1) I get an error message that says something like undefined method 'find' for Foo::User.

How do I call the ActiveRecord User from within Foo?

Thanks.

mwoods79
  • 1,608
  • 1
  • 13
  • 16

1 Answers1

30

Like this:

::User.find(user_id)
Chris Salzberg
  • 27,099
  • 4
  • 75
  • 82
  • I know I tried that and it didn't work. But now it seems to. Can you point to some documentation on why/what this does? – mwoods79 Dec 04 '12 at 04:35
  • 3
    By prepending :: you are accessing the top name-space. Otherwise, ruby will look in your current module. – Ylan S Dec 04 '12 at 04:40
  • I can't find any documentation specifically on this, but it's pretty simple as @ylan-s pointed out. It's just anchoring the reference to the root in the class/module namespace. – Chris Salzberg Dec 04 '12 at 04:41
  • 1
    @mwoods79 You can see few questions about that. http://stackoverflow.com/questions/4829189/what-does-do http://stackoverflow.com/questions/4819312/double-colons-rails – oldergod Dec 04 '12 at 04:56