let's say that I have two classes
class User
attr_accessible :name
has_one :address
validates :name, :presence => true
validates_associated :address
end
class Address
attr_accessible :country, :user_id
belongs_to :user
validates :country, :presence => true
validates :user, :presence => true
end
Now when I try to create an invalid Addressthen it fails (which is good)
a = Address.new
a.valid?
But when I build User with an invalid Address, then it passes (which is bad)
u = User.first
u.build_address
u.valid?
u.save
In this regard, it Userhas Addresswith country => nil.
How can I tell Rails not to save Addressif its invalid?
FIXED: I fixed this by adding a line to the code. Thanks to everyone.
validates_associated :address, :if => :address
source
share