In a Rails 3.1 project, I have a model class with a custom validator:
class Car < ActiveRecord::Base
validate :road_must_exist_nearby, :on => :create
# ...
def not_a_validator_method
Road.exists_nearby?
end
def road_must_exist_nearby
if !Road.exists_nearby?
# ...
end
end
end
When I attempt to save my instance of Car …
> car = Car.new
> car.save
I get the following error:
NameError: uninitialized constant Car::Road
Why does calling Road.exists_nearby? from a normal instance method work?:
> car.not_a_validator_method
=> true
And why does calling it from a validator method raise an error, as though Rails believes Road should be called through Car?:
> car.road_must_exist_nearby
NameError: uninitialized constant Car::Road
And how can I make the validator method work?
I’m only guessing, but I’d say it’s a namespace/scope issue. Rails is interpreting the “Road” constant as existing in the scope of Car (ie Car::Road). You can probably get around it by referencing the global namespace using: “::Road”