与.include一起使用时,Object不支持#inspect

时间:2014-07-27 12:45:34

标签: ruby-on-rails nomethoderror

所以我遇到了一个令人讨厌的错误,我甚至不知道如何调试。我对Rails很陌生,所以这彻底踢了我的屁股。当我在学生的查找中使用.includes(:school)时,它会返回一个nilClass错误,但当我查找任何其他模型并.includes(: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提交查询并使用

执行搜索之前
    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的新手,所以如果我错过了什么,请随意提问。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:3)

students表中,school_id列是否定义为string?直到最近,Rails才不喜欢这样。两个选项:

  1. 升级到最新版本的Rails(截至目前为4.1.4)。
  2. 将列类型更改为整数(或UUID)