【发布时间】:2013-08-12 12:54:47
【问题描述】:
基本组模型:
class Group < ActiveRecord::Base
@@ItemType = 'GroupItem' # Base ItemType
after_initialize :default_item_type
has_many :group_assignments
has_many :items, through: :group_assignments, source: :groupable, source_type: @@ItemType, dependent: :destroy
accepts_nested_attributes_for :items, allow_destroy: true
private
def default_item_type
self.item_type = @@ItemType if self.new_record?
end
end
命名空间模型:
class Gradation::Group < Group
@@ItemType = 'Gradation' # Base ItemType
after_initialize :default_item_type
has_many :group_assignments
has_many :items, through: :group_assignments, source: :groupable, source_type: @@ItemType, dependent: :destroy
accepts_nested_attributes_for :items, allow_destroy: true
private
def default_item_type
self.item_type = @@ItemType if self.new_record?
end
end
我试图在 *after_initialize* 回调上设置一个字段 *item_type*,但无论我做什么,回调只会在常规组模型上触发,而不是在命名空间模型上触发。
我很难理解为什么这是预期的行为,以及如何让回调为命名空间Group工作。
【问题讨论】:
-
试试这个可能有点奇怪,但是你能把
private改成protected吗?如果我没记错的话,私有方法只能由模型使用,而受保护的方法可以由模型及其继承的类使用。此外,回调after_initialize会被调用很多次!每次检索记录时都会调用它。如果要在记录的创建步骤上设置默认值,请改用before_create;)
标签: ruby-on-rails callback rails-activerecord polymorphic-associations