If I have a 'belongs_to' association in a model, I'd like to know the notional difference between validating an association:
class Topping < ActiveRecord::Base
belongs_to :pancake
validates :pancake, presence: true
...
and validating the associated model id:
class Topping < ActiveRecord::Base
belongs_to :pancake
validates :pancake_id, presence: true
...
Motivation:
Some code which assigned a topping to a pancake stopped working at some time in the past. Changing the validation from association to id 'fixed' the problem, but I'd like to know the deeper reason why.
(FYI, when stepping into the code the pancake was valid and in the database and the topping responded to both .pancake
and .pancake_id
appropriately. Both the push operator (pancake.toppings << topping
) and manual assignment and save (topping.pancake = pancake; topping.save
) failed with a pancake missing validation error.)