使用自定义has_many关系时,nil的未定义方法名称

我正在尝试为我的一个模型创建最简单的has_many关系。 它的定义是这样的:

 # i know it doesn't make much sense. I'm using such ridiculous # where case to keep things simple for now has_many :jobs, -> { where(id: 1) }, class_name: SidekiqJob 

然而,当我试图以任何方式调用该关系时,例如使用MyModel.last.jobs ,rails抛出:

 NoMethodError: undefined method `name' for nil:NilClass from /Volumes/HDD/Users/michal/.rvm/gems/ruby-2.1.1/gems/activerecord-4.0.3/lib/active_record/relation/merger.rb:141:in `block in filter_binds' 

有没有人知道这里出了什么问题?

  • ruby2.1.1
  • rails 4.0.3

编辑:

原始关联定义:

 has_many :jobs, (obj) -> { where('jid LIKE ?', "#{obj.superjob_id}%") }, class_name: SidekiqJob 

 has_many :jobs, -> { where(id: 1) }, class_name: SidekiqJob 

如果没有深入查看源代码以查看是否在class_name值上调用了类似to_s内容,则表明语法不正确并且需要在类名称周围使用引号:

 has_many :jobs, -> { where(id: 1) }, class_name: "SidekiqJob" 

请参阅RailsGuides: http ://guides.rubyonrails.org/association_basics.html#scopes-for-has-many-where

 class Author < ApplicationRecord  has_many :confirmed_books, -> { where "confirmed = 1" },    class_name: "Book" end 

来自3_2_release_notes.md:https://github.com/rails/rails/blob/37b36842330b5db1996fda80e387eae3a5781db8/guides/source/3_2_release_notes.md

除了字符串之外,允许关联的:class_name选项采用符号。 这是为了避免让新手感到困惑,并与其他选项保持一致,例如:foreign_key已经允许使用符号或字符串。

 has_many :clients, :class_name => :Client # Note that the symbol need to be capitalized 

事实certificate它与ruby / active_record版本有关。 根据这个线程: 通过关联创建with_many得到NoM​​ethodError(nil的未定义方法`name’:NilClass)

我所做的“修复”是将我的ruby版本改为2.1.10 。 然后,我摆脱了这样的错误(因为他们被扔进了更多的地方)。 无论如何,我仍然无法includes我在OP中定义的关系。 似乎不可能使用custom where语句includes关系。