mbajur mbajur - 1 year ago 69
Ruby Question

Undefined method name for nil when using custom has_many relationship

I'm trying to create the simplest

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

However, when i' trying to call that relationship in anyway, for example with
, 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'

Has anyone have any idea on what is going wrong in here?

  • ruby 2.1.1

  • rails 4.0.3


Original association definition:

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

Answer Source

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)

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download