简体   繁体   中英

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. 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?

Are you sure that all of the father parrots are being saved through the Father object? You should also have a type column in your parrots column that has either 'Parrot' or 'Father' value. When you execute Father.all it should be running a query that looks like this:

SELECT * FROM parrots WHERE type='Father';

filtering out parrots that were not saved through the Father object.

If you just need to pull Parrots that match Father criteria from the DB you can use scopes:

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? Or just a Parrot with certain attributes. It seems that Parrot.all would include all Fathers.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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