简体   繁体   English

在 Rails 中,如何验证属于另一个 model 的 model 上的属性?

[英]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.

相关问题 当一个模型属于 Rails 中的另一个模型时,如何列出它? - How can I list a model when it belongs to a another model in rails? 我如何获得一个模型的关系,该模型属于rails中的另一个模型 - How do I get a relation for a model that belongs_to another model in rails 我如何在模型中对对象属轨中的.count进行计数? - How do I do a .count on the model an object belongs_to in rails? 如何将新创建的对象分配给它在Rails中所属的模型 - How do I assign a newly created object to a model it belongs to in rails 在Rails中,如何将一个模型两次连接到一个多态属于的另一个模型? - In Rails, how to connect a model twice to another model that it polymorphically belongs_to? Rails模型属于一个模型或另一个模型 - Rails model belongs to either one model or another 在Rails中,如何验证特定控制器动作的模型? - In Rails, how do I validate a model for a specific controller action? 如何验证Rails模型中的坐标? - How do I validate coordinates in my Rails model? Rails:如何根据父母的属性验证模型? - Rails: How do I validate model based on parent's attributes? 如何在Rails 3中验证非模型表单? - How do I validate a non-model form in Rails 3?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM