重写ApplicationRecord初始化,坏主意?

时间:2016-12-15 13:35:52

标签: ruby-on-rails activerecord override

我正在创建一个 foo 对象:

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

但是我还需要做其他对象。所以,我想重写 Foo 初始化方法来做这样的事情:

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

那我怎么能这样做?还有其他想法吗?这会初始化压倒一切吗?

2 个答案:

答案 0 :(得分:7)

您可以使用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

答案 1 :(得分:4)

您可以使用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中