[英]In Rails, how do I validate a property on a model that belongs to another model?
I have a book_review model which belongs_to a book model.我有一本 book_review model,它属于一本书 model。
I need to validate that the book that the book_review belongs to has a model called author that is not empty, ie book_review belongs_to book, book.author is not empty我需要验证 book_review 所属的书有一个名为 author 的 model 不为空,即 book_review belongs_to book, book.author 不为空
How can I accomplish this?我怎样才能做到这一点?
You have several choices.你有几个选择。 Here are just a few:
这里仅仅是少数:
delegate :author, to: :book
validates_presence_of :author
validate :book_has_author
private
def book_has_author
book.author.present?
end
belongs_to :author, through: :book
validates_presence_of :author
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.