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

标签 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

最佳答案

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

Allow the :class_name option for associations to take a symbol in addition to a string. This is to avoid confusing newbies, and to be consistent with the fact that other options like :foreign_key already allow a symbol or a string.

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

关于ruby-on-rails - 使用自定义 has_many 关系时 nil 的未定义方法名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38188400/

相关文章:

ruby-on-rails - 删除 mongoid 中的嵌入文档

ruby-on-rails - 传递给 Controller ​​的模型 Rub​​y Rails 验证失败

ruby 公案 : Constants become symbols

ruby-on-rails - 参数丢失或值为空 : user

ruby-on-rails - 将配置文件模型的某些属性设置为对其他用户公开(可见)或私有(private)(不可见)的最佳方法是什么?

ruby-on-rails - 具有用户友谊状态属性的 Mongoid self 引用

javascript - 自动完成功能无法正常工作

ruby-on-rails - 登录后更新属性设计

ruby-on-rails - 警告 : RVM used Gemfile selecting Ruby"

MySQL 与 JRuby 的问题