Paweł Gościcki
Paweł Gościcki

Reputation: 9644

validates_presence_of and unsaved associations

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.

Upvotes: 1

Views: 606

Answers (1)

iHiD
iHiD

Reputation: 2438

Use :inverse_of

class User < ActiveRecord::Base
  has_many :providers, :inverse_of => :user
end

class Provider < ActiveRecord::Base
  belongs_to :user, :inverse_of => :providers
  validates :user, :presence => true
end

Upvotes: 5

Related Questions