活动记录验证 - validates_linked
我不清楚这个方法的实际用途或何时使用它。
假设我有这些模型:
Person < ...
# id, name
has_many :phone_numbers
end
PhoneNumber < ...
# id, number
belongs_to :person
validates_length_of :number, :in => 9..12
end
当我为这样的人创建电话号码时:
@person = Person.find(1)
@person.phone_numbers.build(:number => "123456")
@person.phone_numbers.build(:number => "12346789012")
@person.save
保存失败,因为第一个号码无效。这对我来说是一件好事。但我不明白的是,它是否已经验证关联记录函数 validates_linked 是什么?
I'm unclear on what this method actually does or when to use it.
Lets say I have these models:
Person < ...
# id, name
has_many :phone_numbers
end
PhoneNumber < ...
# id, number
belongs_to :person
validates_length_of :number, :in => 9..12
end
When I create phone numbers for a person like this:
@person = Person.find(1)
@person.phone_numbers.build(:number => "123456")
@person.phone_numbers.build(:number => "12346789012")
@person.save
The save fails because the first number wasn't valid. This is a good thing, to me. But what I don't understand is if its already validating the associated records what is the function validates_associated?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以执行
has_many :phone_numbers, validate: false
并且您看到的验证不会发生。那么为什么要使用
validates_linked
呢?您可能想要执行validates_linked :phone_numbers, on: :create
并跳过更新验证(例如,如果您的数据库中已经存在错误数据,并且您不想为此打扰现有用户)。还有其他场景。根据文档,
has_one
默认情况下是validate: false
。因此,您需要validates_linked
来更改它。You can do
has_many :phone_numbers, validate: false
and the validation you're seeing wouldn't happen.Why use
validates_associated
then? You might want to dovalidates_associated :phone_numbers, on: :create
and skip validation on update (e.g. if there was already bad data in your db and you didn't want to hassle existing users about it).There are other scenarios.
has_one
according to docs isvalidate: false
by default. So you needvalidates_associated
to change that.