【发布时间】:2014-07-27 12:45:34
【问题描述】:
所以我遇到了一个我什至不知道如何调试的严重错误。我对 Rails 还很陌生,所以这彻底让我大吃一惊。当我在 Student 的查找中使用 .includes(:school) 时,它返回一个 nilClass 错误,但是当我通过任何其他模型和 .includes(:school) 查找时,School 表现得很好。
class Student < ActiveRecord::Base
has_many :relationships, foreign_key: "liker_id", dependent: :destroy
has_many :matches, foreign_key: "student_1_id", dependent: :destroy
belongs_to :school
belongs_to :conference
belongs_to :would_you_rather
belongs_to :hometown
belongs_to :year
belongs_to :major
end
class School < ActiveRecord::Base
belongs_to :conference
belongs_to :rival, class: "School", foreign_key: "rival_id"
has_many :students
end
在控制台上
d = Student.where(:id => '1').includes(:school)
SQL 生成
SELECT "schools".* FROM "schools" WHERE "schools"."id" IN (1)
返回错误信息
NoMethodError: undefined method `each' for nil:NilClass
from /.rvm/gems/ruby-2.1.2/gems/activerecord4.1.1/lib/active_record/associations/preloader/association.rb:87:in `block in associated_records_by_owner'
from /.rvm/gems/ruby-2.1.2/gems/activerecord-4.1.1/lib/active_record/associations/preloader/association.rb:86:in `each'
from /.rvm/gems/ruby-2.1.2/gems/activerecord-4.1.1/lib/active_record/associations/preloader/association.rb:86:in `associated_records_by_owner'
from /.rvm/gems/ruby-2.1.2/gems/activerecord-4.1.1/lib/active_record/associations/preloader/singular_association.rb:9:in `preload'
from /.rvm/gems/ruby-2.1.2/gems/activerecord-4.1.1/lib/active_record/associations/preloader/association.rb:20:in `run'
from /.rvm/gems/ruby-2.1.2/gems/activerecord-4.1.1/lib/active_record/associations/preloader.rb:136:in `block (2 levels) in preloaders_for_one'
from /.rvm/gems/ruby-2.1.2/gems/activerecord-4.1.1/lib/active_record/associations/preloader.rb:134:in `each'
from /.rvm/gems/ruby-2.1.2/gems/activerecord-4.1.1/lib/active_record/associations/preloader.rb:134:in `map'
from /.rvm/gems/ruby-2.1.2/gems/activerecord-4.1.1/lib/active_record/associations/preloader.rb:134:in `block in preloaders_for_one'
在使用 .first 提交查询并使用 .first 执行搜索之前
d = Student.where(:id => '1').includes(:school)
控制台生成
Student Load (0.6ms) SELECT "students".* FROM "students" WHERE "students"."id" = 1
School Load (0.2ms) SELECT "schools".* FROM "schools" WHERE "schools"."id" IN (1)
(Object doesn't support #inspect)
=>
并返回一个完全空白的行
我确定错误出在某个地方,我只是不知道如何解决它。我也是 StackOverflow 的新手,所以如果我错过了任何内容,请随时提问。任何帮助表示赞赏。
【问题讨论】:
-
可能你没有 id 为 1 的学生。
-
我最初是这么想的,但昨晚擦除了整个数据库,今天早上通过控制台创建了所有记录。数据库中有 15 名学生。
标签: ruby-on-rails nomethoderror