通过在 rails 中包含 nil 对象错误来查找 [英] Find by include nil object error in rails

查看:27
本文介绍了通过在 rails 中包含 nil 对象错误来查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力解决这个问题,但我真的不知道发生了什么.我有一小段代码:

I've been trying hard to solve this problem but i really don't know what is happening. I have this small piece of code :

DiscoveredLocation.find_by_user_id(user.id, :include => [:boss_kills])

模型是:

DiscoveredLocation(id, user_id, boss_location_id)
BossKill(user_id, monster_id)

和关联:

Monster belongs_to :boss_location
Monster has_many :boss_kills

BossKill belongs_to :user
BossKill belongs_to :monster


DiscoveredLocation belongs_to :user
DiscoveredLocation  belongs_to :boss_location

DiscoveredLocation  has_many :monsters, :through => :boss_location

DiscoveredLocation  has_many :boss_kills, :through => :monsters

当我执行 find_by 时出现此错误:

When i executed the find_by i get this error :

NoMethodError in BossesController#index

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each

如果我将 include 选项更改为任何其他模型,例如 :monster,效果很好.我几乎被这个问题所困扰:P.也许有人可以帮助我?:)

If i change the include option to any other model, like :monster, it works great. I'm pretty much owned by this problem :P. Maybe somebody can help me ? :)

推荐答案

DiscoveredLocation 模型试图通过关联定义嵌套的 has-many:

The DiscoveredLocation model is attempting to define a nested has-many through association:

DiscoveredLocation  has_many :monsters, :through => :boss_location
DiscoveredLocation  has_many :boss_kills, :through => :monsters

我不相信 ActiveRecord 可以开箱即用.有一个 nested_has_many_through 插件声称支持这一点——我不知道它是否适用于这种情况.

I don't believe ActiveRecord can do this out of the box. There is a nested_has_many_through plugin which claims to support this -- I have no idea if it would work in this case.

可以找到更多讨论此处这里

More discussion can be found here and here

这篇关于通过在 rails 中包含 nil 对象错误来查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆