开发者

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. I have a child model(Booking) which 'belongs_to' to 'User' and 'accepts_nested_attributes_for :user'. 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. Basically, the person needs to enter first_name and last_name when creating the booking object. 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

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"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜