说我有两个班级
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
现在当我尝试创建无效的Address
时,它失败了(这很好)
a = Address.new
a.valid? #=> false
但是当我使用无效Address
构建用户时,它会通过(这是不好的)
u = User.first
u.build_address
u.valid? #=> true
u.save #=> true
由于此User
已Address
与country =>为零。
如果Rails无效,我如何告诉Rails不保存Address
?
修复:我通过在代码中添加跟随行来修复此问题。谢谢大家。
validates_associated :address, :if => :address
答案 0 :(得分:1)
class User
attr_accessible :name
has_one :address, :validate => true
validates :name, :presence => true
validates_associated :address
端
答案 1 :(得分:0)
您还需要确认Address
实际存在User
:
class User < ActiveRecord::Base
validates :address, :associated => true, :presence => true
end
有了这个,我得到:
>> u = User.first
=> #<User id: 1, name: "Bob", created_at: "2013-10-09 15:17:21", updated_at: "2013-10-09 15:17:21">
>> u.build_address
=> #<Address id: nil, user_id: 1, country: nil, created_at: nil, updated_at: nil>
>> u.valid?
=> false
>> u.errors
=> #<ActiveModel::Errors:0x007fe1d6919b18 @base=#<User id: 1, name: "Bob", created_at: "2013-10-09 15:17:21", updated_at: "2013-10-09 15:17:21">, @messages={:address=>["is invalid"]}>
>> u.address.errors
=> #<ActiveModel::Errors:0x007fe1d69197a8 @base=#<Address id: nil, user_id: 1, country: nil, created_at: nil, updated_at: nil>, @messages={:country=>["can't be blank"]}>