重写ApplicationRecord初始化,坏主意?

重写ApplicationRecord初始化,坏主意?

问题描述:

我创建一个 obeject这样的:重写ApplicationRecord初始化,坏主意?

@foo = Foo.new(foo_params) 
@foo.bar = Bar.where(name: "baz").first_or_create 

但也有我需要做的这个问题,以及其他对象。所以,我想重写初始化方法做这样的事情的:

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初始化方法。

那么我怎么能做到这一点?任何其他想法?这会初始化压倒性的事情吗?

您可以使用active record callbacks。但是,您将无法指定bar_name,并且将以某种方式需要从Foo属性动态查找它。

如果该选项适用于您。添加到您的模型,如下面的代码。

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,我会建议为它创建一个方法。

Foo.new(params).with_bar

def with_bar(bar_name) 
    self.bar = Bar.where(name: BarName).first_or_create 
end 

您可以使用after_initialize回调,并在必要时使用瞬变:

class Foo < ApplicationRecord 
    after_initialize :custom_initialization 

    attr_accessor :barname 

    def custom_initialization() 
    self.bar = Bar.where(name: self.barname).first_or_create 
    end 
end 

的应用程序记录自己的初始化应该照顾设定barname的提供是在PARAMS

+1

我只会建议你使用'attr_accessor'作为'barname' –

+1

true ...这将是bette r ..我会相应地修改答案。 Ty @NikitaMisharin提供的信息。 – David