【问题标题】:RoR Uninitialized ConstantRoR 未初始化常量
【发布时间】:2014-07-08 17:51:34
【问题描述】:

我有两个班级学生和监护人。第三个类 Stud_guard 管理 Student 和 Guardian 类之间的关系。下面给出了这些类的快照:

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

在代码中,如果我执行@guardian.stud_guards(其中@guardian 包含一个有效的监护人项目),我可以获得一个 stud_guard 条目数组。但是,如果我执行 @student.stud_guards(其中 @student 有一个有效的学生项目),我会收到 "uninitialized constant Student::StudGuards" 错误。我似乎无法理解我在这里缺少什么。

【问题讨论】:

  • 你试过删除foreign_key吗?
  • 好的。当你有has_one 关系时,你正在做@student.stud_guards。所以试试@student.stud_guard

标签: ruby-on-rails ruby ruby-on-rails-2


【解决方案1】:

#has_one 应将模型名称作为单数形式。

has_one  :stud_guard

如果你写has_one :stud_guards,那么它正在寻找一个名为StudGuards的模型,它不存在并且你得到了错误。使用#has_one,Rails 不会在关联名称stud_guards 上应用#singularize 方法,而是在#camelcase 上应用。

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

如果您注意到 “未初始化的常量 Student::StudGuards”,很明显 Rails 搜索模型 StudGuards,正如我从 :stud_guards 中推导出的。但是如果你写stud_guard,它会得到StudGuard,这是你定义的。

希望它现在清除。

【讨论】:

    【解决方案2】:

    试试这个:

    class Student < ActiveRecord::Base
      has_one    :stud_guard, :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
    

    并像这样使用它:

    @student.stud_guard
    

    【讨论】:

      猜你喜欢
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多