经过多次尝试和错误,并寻找一个现有的答案,似乎有一个根本性的误解,我有,并希望得到一些澄清和/或方向。
注意:我正在使用多个表继承,并且有很好的理由这样做,所以不需要指示我回到STI :)
我有一个基本模型:
class Animal < ActiveRecord::Base
def initialize(*args)
if self.class == Animal
raise "Animal cannot be instantiated directly"
end
super
end
end和一个子类:
class Bunny < Animal
has_one(:bunny_attr)
def initialize(*args)
attrs = args[0].extract!(:ear_length, :hop_style)
super
self.bunny_attr = BunnyAttr.create!
bunny_attrs_accessors
attrs.each do |key, value|
self.send("#{key}=", value)
end
def bunny_attrs_accessors
attrs = [:ear_length, :hop_style]
attrs.each do |att|
define_singleton_method att do
bunny_attr.send(att)
end
define_singleton_method "#{att}=" do |val|
bunny_attr.send("#{att}=", val)
bunny_attr.save!
end
end
end
end和一组相关数据
class BunnyAttr < ActiveRecord::Base
belongs_to :bunny
end如果我这样做的话:
bunny = Bunny.create!(name: "Foofoo", color: white, ear_length: 10, hop_style: "normal")
bunny.ear_length
Bunny.first.ear_lengthbunny.ear_length将返回"10",而Bunny.first.ear_length将返回#的“未定义方法'ear_length‘。
为什么是这样,以及如何获得第二个调用来返回值?
发布于 2014-07-01 02:08:25
尝试将当前初始化中的代码移动到after_initialize回调。
after_initialize do
# the code above...
end当ActiveRecord从数据库加载时,它实际上不会调用初始化。当您调用Bunny.first时,ActiveRecord最终调用以下方法:
def find_by_sql(sql, binds = [])
result_set = connection.select_all(sanitize_sql(sql), "#{name} Load", binds)
column_types = {}
if result_set.respond_to? :column_types
column_types = result_set.column_types
else
ActiveSupport::Deprecation.warn "the object returned from `select_all` must respond to `column_types`"
end
result_set.map { |record| instantiate(record, column_types) }
end实例化方法如下所示:
def instantiate(record, column_types = {})
klass = discriminate_class_for_record(record)
column_types = klass.decorate_columns(column_types.dup)
klass.allocate.init_with('attributes' => record, 'column_types' => column_types)
end还有init_with..。
def init_with(coder)
@attributes = self.class.initialize_attributes(coder['attributes'])
@column_types_override = coder['column_types']
@column_types = self.class.column_types
init_internals
@new_record = false
run_callbacks :find
run_callbacks :initialize
self
endinit_internals只设置一些内部变量,如@readonly、@new_record等,因此当您从数据库加载记录时,#initialize永远不会被实际调用。您还会注意到在从db加载时确实运行的run_callbacks :initialize。
上面的代码是从Rails 4.1.1中提取的,但是对于其他最新版本的Rails,大部分初始化过程应该是相同的。
编辑:我只是在考虑这一点,您可以删除定义setter方法的代码,然后如果将方法委托给BunnyAttr,则调用它们。
class Bunny < Animal
has_one :bunny_attr
delegate :ear_length, :hop_style, to: :bunny_attr, prefix: false, allow_nil: false
end这将自动为ear_length和hop_style创建getter和setter,它也将为您跟踪它们的脏状态,允许您在调用bunny上的保存时保存bunny_attr。将allow_nil设置为false将导致ActiveRecord在bunny_attr为nil时抛出错误。
发布于 2014-07-02 00:47:36
Sean在回答中描述的代表团工作得很好,但是我想要一些更通用的东西,因为我将拥有相当多的“动物”,并且不想每次我向BunnyAttr添加一个新的列时都要更新委托行,并且我试图将尽可能多的代码移到动物类上。
然后我偶然发现了这篇博文,并决定在Bunny类中使用method_missing (最终将在动物类中定义一个版本,我将在其中传递attr类)。
def method_missing(method_name, *args, &block)
bunny_attr.respond_to?(method_name) ?
bunny_attr.send(method_name, *args) :
super
end当然会喜欢评论为什么这是一个坏主意,如果有的话。
https://stackoverflow.com/questions/24500809
复制相似问题