I have a rails project similar to a blog with posts that have set of images and one featured image. The image set was a pretty straight forward HABTM relationship, as several posts can share the same image and one post can have many images, but the featured image has been a bit more troubling.
Every post should have one and only one featured image and one image can be the featured image on several posts, so my first thought was just to reverse the relationship and let images has_many
posts and posts belong_to
images, but that seems problematic in a lot of different ways. First, it's not very semantic. Second, the post controller needs extra code to accept a value for image_id, as Post.new didn't seem to want to accept image_id as an attribute.
My second thought --and this is the one I'm going with so far-- was to use a HABTM relationship on both with a limit: 1
specifier on the the post's has_and_belongs_to_many :featured_images
and a unique: true
on t.belongs_to :post
in the migration. This solution works, but it seems hack-ish. Also, it means that I have to access the featured picture like this post.featured_images.first
rather than post.featured_image
. Worse, I can't help but think that this would hurt database performance as it has to access three tables instead of two and it has to search for the post id in the many-to-many table, rather than identifying immeadiately via the id column.
So, is this the right way to do this or is there something better? Does rails have anything like a has_one
, belongs_to_many
relationship?