Call child's method or cast parent to child in Rails
I have some STI structure like following:
class Assignment < ActiveRecord::Base
has_many :criteria, :class_name => "Criterion", :order => :position
end
class Criterion < ActiveRecord::Base
# Represents a criterion used to mark an assignment that
# being the super class for all different criterias
set_table_name "criteria" # set table name correctly
belongs_to :assignment
validates_associated :assignment, :message => 'association is not strong with an assignment'
validates_presence_of :assignment_id
validates_numericality_of :assignment_id, :only_integer => true, :greater_than => 0, :message => "can only be whole number greater than 0"
validates_uniqueness_of :criterion_name, :scope => :assignment_id, :message => 'is already taken'
validates_presence_of :criterion_name,:assignment_id
end
class FlexibleCriterion < Criterion
has_one :flexible_criterion_attribute, :class_name => "FlexibleCriterionAttribute"
accepts_nested_attributes_for :flexible_criterion_attribute
default_scope :include => :flexible_criterion_a开发者_JAVA技巧ttribute
end
class FlexibleCriterionAttribute < ActiveRecord::Base
belongs_to :criterion, :class_name => "FlexibleCriterion"
validates_presence_of :max
validates_numericality_of :max, :message => "must be a number greater than 0.0", :greater_than => 0.0
DEFAULT_MAX = 1
end
Alright, I have uploaded my current working codes. So basically the problem is: When I use a method like criterion = assignment.criteria.find_or_create_by_criterion_name("AAA"), I will get an object of criterion. But I want cast this object to flexiblecriterion so that I can assign the value of criterion.flexible_criterion_attribute
Thx in advance!
- If
assignment.criteria.find_or_create_by_criterion_name("AAA")
returns a record in whichtype
column has valueFlexibleCriterion
, it will automatically cast the object toFlexibleCriterion
. - If you want to ensure that only
FlexibleCriterion
is returned, modify your finder like this:assignment.criteria.find_or_create_by_criterion_name_and_type("AAA", 'FlexibleCriterion')
精彩评论