[英]How to validate a parent model attributes during creation of child model's object?
I have a parent model(User) with optional fields- first_name, last_name and mandatory fields- email and password. 我有一个父模型(用户),带有可选字段-first_name,last_name和必填字段-电子邮件和密码。 I have a child model(Booking) which 'belongs_to' to 'User' and 'accepts_nested_attributes_for :user'.
我有一个子模型(预订),该模型“属于”到“用户”和“ accepts_nested_attributes_for:用户”。 My problem is, whenever the booking object is created, i need to validate the presence of first_name and last_name for the user which is being created/updated.
我的问题是,每当创建预订对象时,我都需要为正在创建/更新的用户验证first_name和last_name的存在。 Basically, the person needs to enter first_name and last_name when creating the booking object.
基本上,此人在创建预订对象时需要输入first_name和last_name。 I have used the 'User' model as parent at many other places but i don't want to add the validation in the 'User' model.
我在许多其他地方都使用过“用户”模型作为父级,但我不想在“用户”模型中添加验证。 I want the validation in the 'Booking' model.
我想要在“预订”模型中进行验证。 How do i accomplish this?
我该如何完成?
If you use validates_associated, it will validate the associated model 如果您使用validates_associated,它将验证关联的模型
class Booking
belongs_to :user
validates_associated :user
end
Extra Credit: http://rpheath.com/posts/412-a-better-validates-associated for getting more in your error message than "User is Invalid" 额外的功劳: http : //rpheath.com/posts/412-a-better-validates-associated用于在错误消息中获得比“用户无效”更多的信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.