【问题标题】:how to get the other side of a polymorphic relationship如何获得多态关系的另一面
【发布时间】:2012-09-18 01:00:55
【问题描述】:
我有以下几点:
class Item < ActiveRecord::Base
# assets
has_many :assets, :as => :assetable, :dependent => :destroy
class Asset < ActiveRecord::Base
belongs_to :assetable, :polymorphic => true
并且希望能够做到:
a=Asset.find(5)
a.item # no dice
如何获取以资产开头的关联项目?
谢谢
【问题讨论】:
标签:
ruby-on-rails
activerecord
polymorphic-associations
【解决方案1】:
为了获取关联的项目,您需要使用您在 Asset 类中设置的关系名称。由于您已将此关系声明为:assetable,因此您需要将该项目称为“资产”。
假设您根据Rails guide 正确设置了数据库,您应该能够执行以下操作:
a=Asset.find(5)
a.assetable
【解决方案2】:
当您创建多态模型(在您的情况下为资产)时,相应的表必须同时具有 _id 和 _type 列才能引用相关的多态记录。在您的情况下,该资产记录需要具有assetable_id 和assetable_type(等于“Item”的字符串)。然后,当您调用 a.item 时,模型知道在“Item”表中查找 id ==assetable_id 的记录。