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