title: Validating associated models in Rails
body: <p>
  I am currently working on a diet tracking app. I have a FoodEntry model where each instance references a single <code>food</code> from another table, and also references a unit of <code>measurement</code> from yet another table.</p>
  
  <pre class="lang-rb prettyprint-override"><code>class FoodEntry &lt; ActiveRecord::Base
    belongs_to :food
    belongs_to :measurement
    validates :food, presence: { message: 'must exist' }
    ...
  end
  </code></pre>
  
  <p>That works fine, but the thing is that each entry in the <code>measurements</code> table is set up (because I'm working with external data) to be associated with a certain <code>food</code>, i.e. a measurement belongs to a food, and a food has many measurements:</p>
  
  <pre class="lang-rb prettyprint-override"><code>class Food &lt; ActiveRecord::Base
    has_many :measurements
    ...
  end
  
  class Measurement &lt; ActiveRecord::Base
    belongs_to :food
    ...
  end
  </code></pre>
  
  <p>My question is, what is the correct way to validate that the specific <code>measurement</code> I'm referencing in a <code>food_entry</code> is also one of its <code>food.measurements</code>?</p>
  
  <p>Currently in my <code>FoodEntry</code> model I'm doing this:</p>
  
  <pre class="lang-rb prettyprint-override"><code>validate :measurement_must_be_associated
  
  def measurement_must_be_associated
    unless food.measurements.include? measure
      errors.add(:measurement, 'is not associated with that food')
    end
  end
  </code></pre>
  
  <p>This custom validation works, but I'm not sure it's the cleanest way to do it. </p>
  
  <p>I attempted to do this instead:</p>
  
  <pre class="lang-rb prettyprint-override"><code>validates :measurement, inclusion: { in: food.measurements }
  </code></pre>
  
  <p>but this gives me an error when calling <code>FoodEntry.new(food_id: 1, measurement_id: 1)</code> in the rails console (actual <code>id</code>s are irrelevant):</p>
  
  <pre class="lang-none prettyprint-override"><code>NameError: undefined local variable or method `food' for FoodEntry (no database connection):Class
  </code></pre>
  
  <p>Using <code>in: self.food.measurements</code> in the validation made no difference. Help?</p>