2

假设我有两节课

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

由于这UserAddress国家=>无。

如果Rails 无效,我如何告诉Address它不要保存?

修复:我通过在代码中添加后续行来解决此问题。谢谢大家。

validates_associated :address, :if => :address
4

2 回答 2

1
class User
  attr_accessible :name

  has_one :address, :validate => true

  validates :name, :presence => true
  validates_associated :address

结尾

于 2013-10-09T13:50:13.993 回答
0

您还需要验证 anAddress实际上存在于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"]}>
于 2013-10-09T15:28:40.027 回答