[英]add validations to inherited model in rails 4
The code is simply inherited model. 该代码只是继承的模型。 But unfortunately validation does not work. 但是不幸的是验证不起作用。 The idea is to select fathers from parrots. 这个想法是从鹦鹉中选择父亲。 When I loop @fathers - it shows all parrots but should select only those who have age more than 12 and so on. 当我循环@fathers时-它显示了所有的鹦鹉,但是应该只选择年龄大于12岁的那些,依此类推。 Or maybe I do something wrong? 还是我做错了什么?
Model 模型
class Father < Parrot
has_many :parrots
validates :age, :numericality => { :greater_than => 12}
validates :tribal, :acceptance => true
validates_inclusion_of :sex, :in => %w( Male )
end
view 视图
<% @fathers.each do || %>
<%= f.name %>
<% end %>
controller 调节器
def index
@parrots = Parrot.all
@fathers = Father.all
end
The validation criteria has nothing to do with how data is queried, just that it passes the defined criteria before object is written to the database. 验证标准与如何查询数据无关,只是在对象写入数据库之前数据已通过定义的标准。 Are you saying that Father
object doesn't perform the validation and persists invalid data? 您是说Father
对象不执行验证并保留无效数据吗?
Are you sure that all of the father parrots are being saved through the Father
object? 您确定所有父级鹦鹉都通过“ Father
对象保存了吗? You should also have a type
column in your parrots
column that has either 'Parrot' or 'Father' value. 您的parrots
列中还应该有一个type
列,该列具有“鹦鹉”或“父亲”值。 When you execute Father.all
it should be running a query that looks like this: 当您执行Father.all
它应该正在运行如下查询:
SELECT * FROM parrots WHERE type='Father';
filtering out parrots that were not saved through the Father
object. 过滤掉没有通过Father
对象保存的鹦鹉。
If you just need to pull Parrots
that match Father
criteria from the DB you can use scopes: 如果只需要从数据库中提取与Father
条件匹配的Parrots
,则可以使用范围:
class Father < ActiveRecord::Base
self.table_name = 'parrots'
default_scope { where("age > 12 and tribal = 'true' and sex='Male'")}
#whatever else
end
Here's additional information on Single Table Inheritance and scopes 这是有关单表继承和范围的其他信息
Validations are used when the Father is saved. 当父亲被保存时,将使用验证。 The "type" column in the db will determine the class. 数据库中的“类型”列将确定类。 Be sure that is set correctly. 确保正确设置。
But, is Father
really a separate class? 但是, Father
真的是一个单独的班吗? Or just a Parrot
with certain attributes. 或者只是具有某些属性的Parrot
。 It seems that Parrot.all would include all Fathers. 似乎Parrot.all将包括所有父亲。
It may be a scope. 这可能是一个范围。
class Parrot < ActiveRecord::Base
scope :fathers, -> { where(:sex => 'Male').where('age >= 12').where(:tribal => true) }
end
Then you can get fathers by 那你就可以得到父亲
@fathers = Parrot.fathers
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.