我一直在努力解决这个问题,但我真的不知道发生了什么。我有一小段代码:
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时,我收到此错误:
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。也许有人可以帮助我? :)
答案 0 :(得分:0)
我可能错了,但要帮助你,请尝试DiscoveredLocation.find_by_user_id(user.id, :include => [:boss_kill])
最后,您确定要将名为user的变量传递给控制器吗?也许是current_user,如果你使用的是流行的auth gem?
答案 1 :(得分:0)
您还需要包含中间表,否则无法将boss_kills映射到DiscoveredLocations:
DiscoveredLocation.find_by_user_id(user.id, :include => [:monsters, :boss_locations,:boss_kills])
另外,请检查开发日志以查看生成的查询。如果可能,请在此处发布,以便我们确定是否缺少其中一个中间表。
答案 2 :(得分:0)
DiscoveredLocation模型正在尝试通过关联定义嵌套的has-many:
DiscoveredLocation has_many :monsters, :through => :boss_location
DiscoveredLocation has_many :boss_kills, :through => :monsters
我不相信ActiveRecord可以开箱即用。有一个nested_has_many_through插件声称支持这个 - 我不知道它是否适用于这种情况。