也许我忽略了一些明显的东西,但我正在尝试将一个实际场景应用到这个 rails for Zombies 教程中。
--------问题------------ 假设正确定义了模型和关系,找到所有属于 Zombie 'Ash' 的武器。
class Zombie < ActiveRecord::Base
has_many :weapons
end
class Weapon < ActiveRecord::Base
belongs_to :zombie
end
本教程接受以下答案-
z = Zombie.find(1)
[#<Zombie id: 1, name: "Ash", graveyard: "Glen Haven Memorial Cemetery">]
z.weapons
[#<Weapon id: 1, name: "Hammer", strength: 1, zombie_id: 1>]
但对我来说这不太实际,就好像我正在做这个项目,遇到这类问题我会这样做。
ash = Zombie.where(:name => "Ash")
[#<Zombie id: 1, name: "Ash", graveyard: "Glen Haven Memorial Cemetery">]
但是
ash.weapons
给出输出
#<NoMethodError: undefined method `weapons' for #<ActiveRecord::Relation:0x00000016334738>>
当查找僵尸的输出完全相同并且考虑到问题的构成方式(即使它们提供了数据库表),我发现僵尸的方式更加实用时,这怎么可能呢?这可能是代码学校交互式控制台的细微差别,还是我遗漏了什么?
感谢您的关注。
最佳答案
正如您的结果所示:
[#<Zombie id: 1, name: "Ash", graveyard: "Glen Haven Memorial Cemetery">]
这是某种强化数组。 所以如果你愿意:
ash = Zombie.where(:name => "Ash").first
ash.weapons
将归还所有武器。
关于database - 关系发现误会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14371670/