2013-02-13 183 views
1

我使用:我的班级正在调用一个不存在的班级?

  • 的Ruby 1.9.2
  • 的Rails 3.1.10

这是我的代码:

class Report::ExpectedHour 

    def initialize(user, options = {}) 
    @user  = user 
    @date_start = options[:start] 
    @date_end = options[:end] 
    end 

    def expected_hours_range 
    previous = ExpectedHour.previous_dates(@user, @date_start).first 
    hours_range = ExpectedHour.between_dates(@user, @date_start, @date_end) 

    unless hours_range.include?(previous) 
     hours_range << previous 
    end 

    hours_range 
    end 

end 

每次我打电话expected_hours_range从我的实例我得到这个错误:

NameError: uninitialized constant Report::ExpectedHour::ExpectedHour 
from /home/edelpero/.rvm/gems/[email protected]/gems/aws-s3-0.6.2/lib/aws/s3/extensions.rb:206:in `const_missing_from_s3_library' 
from /opt/lampp/htdocs/titi/app/models/report/expected_hour.rb:10:in `expected_hours_range' 

我不确定为什么Report::ExpectedHour::ExpectedHour被调用,因为我打电话ExpectedHour这是一个实际存在的ActiveRecord类。另外Report::ExpectedHour::ExpectedHour不存在。

+0

前缀: – 2013-02-13 14:13:10

回答

2

在你的类方法内部调用类时,ruby希望它是嵌套在你自己类中的类或者是一个常量。试试这个:

class MyClass 
    def some_method 
    use_external_class = ::ExternalClass::CONSTANTB.bla 
    # Use the '::' 
    end 
end 
+0

谢谢戴夫牛顿和nicooga为你解释,它的工作原理非常完美。我有另一个问题。那么为什么在我的ActiveRecord类中,当调用另一个模型时,我不需要使用::?再次感谢。 – edelpero 2013-02-13 14:20:46

+0

不要在您的评论中提出另一个问题。搜索堆栈溢出的答案,并且,如果它没有出现,为这个特定的事情创建一个新的问题。 – 2013-02-13 14:26:53

相关问题