Search code examples
ruby-on-railsrubyruby-on-rails-2

RoR Uninitialized Constant


I have two classes Student and Guardian. A third class Stud_guard governs the relationship between Student and Guardian classes. A snapshot of the classes is given below:

class Student < ActiveRecord::Base
    has_one    :stud_guards, :foreign_key => 'student_id', :dependent=>:destroy
end

class Guardian < ActiveRecord::Base
    has_many   :stud_guards, :dependent=>:destroy
end

class StudGuard < ActiveRecord::Base
    belongs_to :student_id, :class_name => 'Student'
    belongs_to :guardian_id, :class_name => 'Guardian'
end

In the code, if I execute @guardian.stud_guards (where @guardian contains a valid guardian item), I'm able to obtain an array of stud_guard entries. However, if I execute @student.stud_guards (where @student has a valid student item), I get an "uninitialized constant Student::StudGuards" error. I cant seem to understand what I'm missing here.


Solution

  • #has_one should take the model name as singular form.

    has_one  :stud_guard
    

    If you write has_one :stud_guards, then it is looking for a model named as StudGuards, which doesn't exist and you got the error. With #has_one, Rails wouldn't apply #singularize method on the association name , stud_guards, but #camelcase.

    'stud_guards'.camelcase # => "StudGuards" 
    'stud_guard'.camelcase # => "StudGuard" 
    

    If you notice "uninitialized constant Student::StudGuards", it is clear that Rails search for the model StudGuards, which it deduced as I said from :stud_guards. But If you write stud_guard, it would get StudGuard, which you have defined.

    Hope it clears now.