简体   繁体   English

基于给定模型的Rails条件验证

[英]Rails conditional validation based on a given Model

I didn't define the problem correctly the first time. 我第一次没有正确定义问题。 I tried to make a simple example and failed. 我试图举一个简单的例子,但失败了。 Let's try again :) 让我们再试一次 :)

I have an Address Model that validates the street, city, state, and zip attributes all exist. 我有一个地址模型,用于验证街道,城市,州和邮政编码属性是否全部存在。 Then we have a Person Model that has a one to many relationship with Address. 然后我们有了一个人模型,它与地址具有一对多的关系。 We have a student model but it DOESN'T inherit off person, it just has_one (I didn't completely understand how inheritance worked in ruby when I started). 我们有一个学生模型,但它不会继承人,只是has_one(我刚开始时并不完全了解继承是如何在ruby中工作的)。 We have a Classroom model that also has_on person (again, not inherited.) So the issue is we want to require an address for the student, but not the Classroom. 我们有一个教室模型,该模型也具有on_on人(再次,不是继承的)。因此,问题是我们希望为学生提供一个地址,而不是教室。 Hopefully this is a little more clear now. 希望这现在更加清楚了。 Thanks! 谢谢!

You can use validates or validates_presence_of in only your Student model. 您只能在Student模型中使用validatesvalidates_presence_of

class Person
  has_many :addresses
end

class Student < Person
  validates :addresses, :presence => true
end

class Teacher < Person
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM