简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM