timpone
timpone

Reputation: 19969

how to get the other side of a polymorphic relationship

I have the following:

class Item < ActiveRecord::Base
  # assets
  has_many :assets, :as => :assetable, :dependent => :destroy

class Asset < ActiveRecord::Base
  belongs_to :assetable, :polymorphic => true

And would like to be able to do:

a=Asset.find(5)
a.item  # no dice

How would I get the associated item starting with the asset?

thx

Upvotes: 2

Views: 181

Answers (2)

Peter Brown
Peter Brown

Reputation: 51697

In order to get the associated item, you need to use the relationship name that you setup in the Asset class. Since you have declared this relationship as :assetable, you need to refer to the item as "assetable".

Assuming you have your database setup correctly according to the Rails guide, you should be able to do the following:

a=Asset.find(5)
a.assetable

Upvotes: 2

cdesrosiers
cdesrosiers

Reputation: 8892

When you create a polymorphic model (Asset in your case), the corresponding table has to have both an _id and a _type column to refer to the related polymorphic record. In your case, this asset record needs to have assetable_id and assetable_type (a string equal to "Item"). Then, when you call a.item, the model knows to look in the "Item" table for the record with id == assetable_id.

Upvotes: 1

Related Questions