I have a product, and a product can have many images. This is through an associations table. However, I would like a product to have one main image.
I know this is very easy to do with a method in the model, but I want it to be an association so that I can preload it in the query by using include
.
Models:
class Product < ActiveRecord::Base
has_many :image_associations, :as => :imageable
has_many :images, :through => :image_associations
end
class ImageAssociation < ActiveRecord::Base
belongs_to :image
belongs_to :imageable, :polymorphic => true
end
class Image < ActiveRecord::Base
has_many :image_associations
end
In the ImageAssociation table, there is a boolean column called 'feature' which associates an image as the 'main' image.
One of the ways I've thought about doing this is adding a main_image_id
column to the products table, and then adding to the Image
model:
belongs_to :image, :class => "Image", :foreign_key => "main_image_id"
However, this doesn't allow for any fallback to the other has_many images if the main image is nil -- which I'd like the association to load.
Which is why I was hoping for something in the images model like:
has_one :image, :through => :images, :conditions => 'feature = true', :order => 'created_at DESC'
But that gives me an association error.
Is there any way I can edit that has_one, or do I really need to run a rake task to push an image into every main_image_id field, and then add a validation for future products to make sure a main image has been added?
EDIT:
Should I be using a has_and_belongs_to_many
association instead?
They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.
Rails supports six types of associations: belongs_to.
Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.
Self-referential association means we create a JOIN MODEL, such as Friendship, for example, which links another model, such as User to itself, so a user can have many friends (which are other users), and a friend can be befriended by a user ( a follower and a followed).
You're almost there, I think, although I'm not so clear on polymorphic associations. I think you want the following:
has_one :main_image_assoc, class => "ImageAssociation", :conditions => 'feature = true', :order => 'created_at DESC', :as => :imageable
has_one :image, :through => :main_image_assoc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With