title: Rails model with associated images and selecting main image for this model
body: <p>I want to ask about, how can you properly select main image from association of images after you update main_image and delete more couple images etc.
  <br/>I have this code: 
  <br/>It's the main model:</p>
  
  <pre><code>class Gallery &lt; ApplicationRecord
    has_many :paintings, inverse_of: :gallery
    belongs_to :primary_painting, class_name: 'Painting', required: false
    accepts_nested_attributes_for :paintings, reject_if: :all_blank, allow_destroy: true
  
    before_validation :primary_painting_setup
  
    private
  
    def primary_painting_setup
      self.primary_painting = paintings.any? ? paintings.select(&amp;:primary?).first || paintings.first : nil
    end
  end
  </code></pre>
  
  <p>And this is associated model:</p>
  
  <pre><code>class Painting &lt; ApplicationRecord
    belongs_to :gallery, inverse_of: :paintings
    has_attached_file :image, styles: { medium: '300x300&gt;', thumb: '100x100&gt;' }, default_url: '/images/:style/missing.png'
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
  end
  </code></pre>
  
  <p>Basically, gallery has main_image on index page, which is chosen from associate paintings.<br/>
  But f.e. if I delete all images and add a new one and set it as main image. It won't work, because on the stage of <code>before_validation</code> I have only old images, which aren't useful for me at all.</p>
  
  <p>Of course I can use a helper or model method such as <code>gallery.paintings.find(:&amp;main_image_bool)</code> every time I render a gallery, but it costs too much speed.</p>
  
  <p>Can you advise more proper way to choose this? Maybe there's a <strong>magic</strong> association, that will help.</p>