覆盖ApplicationRecord初始化,不好的主意吗? [英] Overriding ApplicationRecord initialize, bad idea?
问题描述
我正在创建一个 foo 对象,如下所示:
I am creating a foo obeject like this:
@foo = Foo.new(foo_params)
@foo.bar = Bar.where(name: "baz").first_or_create
但是我还需要执行其他操作.因此,我想到了重写 Foo 初始化方法来执行以下操作:
But there are other objects that I will need to do this as well. So, I thought of overriding the Foo initialize method to do something like this:
class Foo < ApplicationRecord
def initialize(*args, BarName)
@foo = super
@foo.bar = Bar.where(name: BarName).first_or_create
end
end
并这样称呼它:
@foo = Foo.new(foo_params, "baz")
但是Foo是ApplicationRecord,似乎不建议覆盖ApplicationRecord的initialize方法.
But Foo is an ApplicationRecord and it seems that it's not recommended to override the ApplicationRecord initialize method.
那我该怎么办呢?还有其他想法吗?初始化覆盖的东西行得通吗?
So how could I do this? Any other ideas? Would this initialize overriding thing work?
推荐答案
您可以使用活动记录回调一个>.但是,您将无法指定bar_name,并且需要以某种方式从Foo属性中动态找到它.
You can use active record callbacks for that. However you won't be able to to specify bar_name and will somehow need to find it dynamically from Foo attributes.
如果该选项对您有用.将类似以下代码的内容添加到模型中.
If that option works you. Add to your model something like the the following code.
after_initialize :set_bar
# some other code
def set_bar
name = # dynamicly_find_name
self.bar = Bar.where(name: name).first_or_create
end
如果您确实需要指定bar_name
,我建议为其创建一个方法.
In case you really need to specify bar_name
, I would suggest to create a method for it.
Foo.new(params).with_bar
def with_bar(bar_name)
self.bar = Bar.where(name: BarName).first_or_create
end
这篇关于覆盖ApplicationRecord初始化,不好的主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!