title: Ruby on Rails has_many through association objects before save
body: <p>on a Ruby on Rails project I'm trying to access association objects on an ActiveRecord prior to saving everything to the database. </p>
  
  <pre><code>class Purchase &lt; ActiveRecord::Base
  
    has_many :purchase_items, dependent: :destroy
    has_many :items, through: :purchase_items
  
    validate :item_validation
  
    def item_ids=(ids)
      ids.each do |item_id|
        purchase_items.build(item_id: item_id)
      end
    end
  
    private
  
    def item_validation
      items.each do |item|
        ## Lookup something with the item
        if item.check_something
          errors.add :base, "Error message"
        end
      end
    end
  
  end
  </code></pre>
  
  <p>If I build out my object like so:
  <code>purchase = Purchase.new(item_ids: [1, 2, 3])</code> and try to save it the <code>item_validation</code> method doesn't have the items collection populated yet, so even though items have been set set it doesn't get a chance to call the <code>check_something</code> method on any of them.  </p>
  
  <p>Is it possible to access the items collection before my purchase model and association models are persisted so that I can run validations against them? </p>
  
  <p>If I change my <code>item_validation</code> method to be:</p>
  
  <pre><code>def item_validation
    purchase_items.each do |purchase_item|
      item = purchase_item.item
      ## Lookup something with the item
      if item.something
         errors.add :base, "Error message"
      end
    end
  end
  </code></pre>
  
  <p>it seems to work the way I want it to, however I find it hard to believe that there is no way to directly access the items collection with rails prior to my purchase and associated records being saved to the database.</p>