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_attribute
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
好的,我上传了我当前的工作代码。基本上问题是: 当我使用像criterion = assignment.criteria.find_or_create_by_criterion_name(“AAA”)这样的方法时,我将得到一个标准对象。但是我希望将此对象转换为flexiblecriterion,以便我可以赋值standard.flexible_criterion_attribute
Thx in advance!
答案 0 :(得分:1)
assignment.criteria.find_or_create_by_criterion_name("AAA")
返回type
列的值为FlexibleCriterion
的记录,则会自动将对象转换为FlexibleCriterion
。FlexibleCriterion
,请修改您的查找器,如下所示:assignment.criteria.find_or_create_by_criterion_name_and_type("AAA", 'FlexibleCriterion')