Note that there are some explanatory texts on larger screens.

plurals
  1. PORails featured image association?
    primarykey
    data
    text
    <p>I've been trying to figure out how to associate my models on a project I've been working on for a while, and I've come here for help a couple times before, but I never got a satisfactory answer. I have two models: Post and Image. Every post has several images attached to it and posts can share images, so a HABTM relationship made sense for that, like this:</p> <pre><code>class Post &lt; ActiveRecord::Base has_and_belongs_to_many :images end class Image &lt; ActiveRecord::Base has_and_belongs_to_many :posts end </code></pre> <p>The problem now is that I want each post to have a single 'featured image.' How do I do this? The first thought that comes to mind is a simple <code>has_one :featured_image</code> on the post and <code>belongs_to :post_featured_on</code> on the image, but the problem with that is that the same image can be featured on multiple posts.</p> <p>So the next idea I came up with is to reverse the relationship: <code>belongs_to :featured_image</code> on the post and <code>has_many :posts_featured_on</code> on the image. The problem with that is that it isn't very semantic and rails doesn't seem to want to let me set a post's featured image from its form, like this in the controller: <code>Post.new(:featured_image =&gt; Image.find(params[:image_id]))</code></p> <p>So the next idea suggested to me was a second HABTM relationship, like so: <code>has_and_belongs_to_many :featured_images</code>. There's an obvious problem with this, it's plural. I tried putting <code>unique: true</code> on the post_id column in the migration, but that didn't help the fact that I kept having to do this in my code: <code>post.featured_images.first</code> which can be very frustrating.</p> <p>The last idea I tried was a <code>has_many :posts, through: :attachment</code> and <code>has_one :featured_posts, through: :attachment</code> in place of the original HABTM, but these just seems unnecessarily cumbersome, and rails doesn't seem to want to let me assign the images on the fly this way like <code>Post.new(:featured_image =&gt; Image.find(params[:image_id]))</code>.</p> <p>Is there any good way to do this? Have I done something wrong in my previous attempts? Shouldn't this just be a simple foreign key on the post table? Why does it have to be so difficult?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload