I would like to associate a â??productâ?? model with 3 models inherited from
â??imageâ??: part, action and accessory.
I have it working with Has_many :through relating products to images
through attachments, I then have to determine the â??typeâ?? of the STI
extension. This means i have to go product.images. While this is ok, i
can see it getting tricky when i want to go products.images <<
Part.create(:name => “test”). (im on edge rails so the << should work)
I would like to have the parts, actions or accessories collections
available under products eg products.parts.
I have the following tables: product - attachment - images, each with
their own model.
I also have 3 models that inherit from image eg Part < Image.
Ive been following the hasmanythrough article ‘the other side of
polymorphic’. As well as read most of the other articles…but i just
dont get how this will work.
According to the docs has_many ignores class_name when using :through.
“Options for :class_name and :foreign_key are ignored, as the
association uses the source reflection.”
-
Attachment tables:
-
(polymorphic attempt)
-
create_table “attachments”, :force => true do |t|
-
t.column “product_id”, :integer
-
t.column “attachable_id”, :integer
-
t.column “attachable_type”, :string
-
t.column “created_at”, :datetime
-
t.column “created_by”, :integer
-
end
-
Models:
-
class Product < ActiveRecord::Base
-
has_many :parts, :through => :attachments,
-
:class_name => :parts,
-
:conditions => “attachments.attachable_type = ‘Image’”
-
end
-
class Attachment < ActiveRecord::Base
-
belongs_to :product
-
belongs_to :attachable, :polymorphic => true
-
belongs_to :part, :class_name => “Part”,
-
:source => :image,
-
:foreign_key => “attachable_id”
-
end
-
class Part < Image
-
has_many :attachments, :as => :attachable
-
has_many :products, :through => :attachments
-
end
Through the console i can do the following:
- Part.find(:first).products.count
-
1
But this fails
- Product.find(:first).parts
-
ActiveRecordHasManyThroughSourceAssociationNotFOundError
- …
- …
- …
- associations.rb:876: in ‘parts’
This is what i need to work and it doesnt. The many models are the ones
that can access the shared models…but not the reverse…hmmm. Thats a
pain if your shared model
Also, i still have no idea how to create the association with
polymorphism. Its easy with just :through ! Im going to go back to the
:through association as it makes more sense to me.
Would love to hear that im really close and just need to change x and
y… =)