Greets to ruby developers.
I'm stuck with ActiveRecord model associations. I illustrate what I want to do by a tables. I have these tables:
Products: +----+-----------+ | id | name | +----+-----------+ | 1 | Cellphone | +----+-----------+ Images: +----+-------+--------------+----------------+ | id | url | imageable_id | imageable_type | +----+-------+--------------+----------------+ | 1 | 1.jpg | 1 | Product | | 2 | 2.jpg | 1 | Product | | 3 | 3.jpg | 777 | User | # User for example +----+-------+--------------+----------------+ Photos: +----+----------+--------------+----------------+-------+ | id | image_id | photoable_id | photoable_type | cover | +----+----------+--------------+----------------+-------+ | 1 | 1 | 1 | Product | 0 | | 2 | 2 | 1 | Product | 1 | | 3 | 23 | 7 | Service | 1 | # Service for example +----+----------+--------------+----------------+-------+
Any model can have many images (e.g. User has many avatars). Product can have many images, but one of these images must be a product cover (a main image). So I add a Photo model with 'cover' flag. Photo must be associated with Image.
Models:
class Product < ActiveRecord::Base
# need assocs
end
class Image < ActiveRecord::Base
# need assocs
end
class Photo < ActiveRecord::Base
# need assocs
end
I want to get something like this:
p = Product.find(1)
p.images.each do |image|
# As you can see, cover attribute included to result set
puts "Image url: #{image.url}, Is cover: #{image.cover ? 'yes' : 'no'}"
end
Please help me with associations between models