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

时间:2016-07-04 15:43:20

标签: ruby-on-rails ruby activerecord

我正在尝试为我的某个模型创建最简单的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'

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

  • ruby​​ 2.1.1
  • rails 4.0.3

编辑:

原始协会定义:

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

2 个答案:

答案 0 :(得分:1)

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

如果没有深入查看源代码以查看to_s值上是否有类似class_name的内容,则会显示语法错误,并且需要在类名称周围加上引号:

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

答案 1 :(得分:0)

原来它与ruby / active_record版本有关。根据这个帖子:create with has_many through association gets NoMethodError (undefined method `name' for nil:NilClass)

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

相关问题