2013-01-07 2 views
3

다음과 같이 나는 세 가지 클래스 정의 : 나는 콘솔 입력 불 경우단일 테이블 상속을 알 수없는 하위 클래스

class Animal < ActiveRecord::Base 
    attr_accessible :animal_definition_id, :aquarium_id 

    belongs_to :animal_definition 
    belongs_to :aquarium 

    has_many :comments, as: :commentable 
end 

class Fish < Animal 
end 

class Coral < Animal 
end 

는 :

Coral.all 

를 내가 얻을 :

NameError: uninitialized constant Coral 
    from (irb):1 
    from /Users/gjr/.rvm/gems/[email protected]/gems/railties-3.2.10/lib/rails/commands/console.rb:47:in `start' 
    from /Users/gjr/.rvm/gems/[email protected]/gems/railties-3.2.10/lib/rails/commands/console.rb:8:in `start' 
    from /Users/gjr/.rvm/gems/[email protected]/gems/railties-3.2.10/lib/rails/commands.rb:41:in `<top (required)>' 
    from script/rails:6:in `require' 
    from script/rails:6:in `<main>' 

지금 ... Animal.all을 입력하면 예상대로 작동합니다. 그리고 나서 Coral.all이 잘 작동합니다!

산호가 작동하기 전에 동물을 참조해야하는 이유는 무엇입니까? 그건 그렇고, 만약 내가 all이 아닌 다른 행동을한다면 같은 행동을한다. Coral.class 같은 일을합니다.

실제 응용 프로그램에서이 동작을 보지 못했지만 이상한 버그가 발생하기를 기다리고 있습니다.

감사합니다.

답변

4

레일스는 모델이 호출 될 때 동적으로 모델을로드합니다. 따라서 처음에 Animal.all으로 전화를 걸면 Rails가 models/animal.rb 파일을 찾아로드합니다. 다른 클래스도 해당 시간에로드됩니다. 에 관계없이 Animal가 또는하지로드되었는지 여부 CoralFish를 호출 할 수있게하려면

, 그냥 파일 models/coral.rbmodels/fish.rb에 넣어. 그것은 당신을 위해 일해야합니다.

관련 문제