本文介绍了使用自定义has_many关系时nil的未定义方法名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的一个模型创建最简单的 has_many 关系。定义如下:

I'm trying to create the simplest has_many relationship possible for one of my models. It's defined like that:

# 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 的关系,都会抛出异常:

However, when i' trying to call that relationship in anyway, for example with MyModel.last.jobs, rails throws:

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'

有人对它有任何想法


  • 红宝石2.1.1

  • 轨道4.0.3
  • ruby 2.1.1
  • rails 4.0.3

原始关联定义:

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


推荐答案

原来与ruby / active_record版本有关。根据此线程:

It turned out to be related to ruby/active_record versions. According to this thread: create with has_many through association gets NoMethodError (undefined method `name' for nil:NilClass)

我为修复红宝石版本所做的操作为 2.1.10 。然后,我摆脱了此类错误(因为它们被扔到了更多地方)。无论如何,我仍然无法 includes 我的关系。似乎不可能使用自定义where语句包括关系。

What i've done to "fix" that was to change my ruby version to 2.1.10. Then, i got rid of such errors (cause they've been thrown in more places). Anyway, i am still not able to includes my relation defined as in the OP. It seems that it's not possible to includes relations using custom where statements.

这篇关于使用自定义has_many关系时nil的未定义方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 14:19