【问题标题】:add validations to inherited model in rails 4向 Rails 4 中的继承模型添加验证
【发布时间】:2016-03-30 05:04:38
【问题描述】:

代码只是继承模型。 但不幸的是,验证不起作用。这个想法是从鹦鹉中选择父亲。当我循环@fathers - 它显示所有鹦鹉,但应该只选择那些年龄超过 12 岁的鹦鹉,依此类推。或者我做错了什么?

型号

  class Father < Parrot
  has_many :parrots
    validates :age, :numericality => { :greater_than => 12}
    validates :tribal, :acceptance => true
    validates_inclusion_of :sex, :in => %w( Male )
  end

查看

  <% @fathers.each do || %>
    <%= f.name %> 
  <% end %>

控制器

  def index
    @parrots = Parrot.all
    @fathers = Father.all
  end

【问题讨论】:

    标签: ruby-on-rails validation model-view-controller


    【解决方案1】:

    当父亲得救时使用验证。数据库中的“类型”列将确定类。确保设置正确。

    但是,Father 真的是一个单独的类吗?或者只是具有某些属性的Parrot。 Parrot.all 似乎会包括所有的父亲。

    它可能是一个范围。

    class Parrot < ActiveRecord::Base
    
      scope :fathers, -> { where(:sex => 'Male').where('age >= 12').where(:tribal => true) }
    
    end
    

    那么你可以通过

    @fathers = Parrot.fathers
    

    【讨论】:

    • 谢谢。这就是解决方案。
    【解决方案2】:

    验证标准与如何查询数据无关,只是在将对象写入数据库之前通过了定义的标准。你是说Father 对象不执行验证并保留无效数据?

    你确定所有的父亲鹦鹉都通过Father 对象被保存了吗?您的parrots 列中还应该有一个type 列,该列具有“Parrot”或“Father”值。当您执行Father.all 时,它应该运行如下查询:

    SELECT * FROM parrots WHERE type='Father';
    

    过滤掉未通过Father 对象保存的鹦鹉。

    如果您只需要从数据库中提取与Father 条件匹配的Parrots,您可以使用范围:

    class Father < ActiveRecord::Base
       self.table_name = 'parrots'
       default_scope { where("age > 12 and tribal = 'true' and sex='Male'")}
       #whatever else
    end
    

    这里是关于Single Table Inheritance 和scopes 的更多信息

    【讨论】:

    • 谢谢。这就是解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    相关资源
    最近更新 更多