Take the following code (Rails 3.0.10):
User < AR
has_many :providers
Provider < AR
belongs_to :user
validates_presence_of :user
user = User.new
user.providers.build
# so both models not yet saved but associated with each other
user.valid?
=> false
user.errors
=> {:providers=>["is invalid"]}
user.providers.first.errors
=> {:user_id=>["can't be blank"]}
Why can’t Provider see that it has a not yet saved associated user model available? Or in other words – how can I deal with that so that the validation is still present? Or maybe I’m doing something wrong?
Note, that I’m looking for a clean solution, so suggesting a before validation callback in Provider model saving the User model to the database is a no-go.
Use :inverse_of