如何使用'创建!'带有一个参数的构造函数的类的方法

时间:2018-05-28 06:50:15

标签: ruby rails-activerecord

我有一个看起来像这样的课程(简化)

class Timereg < ActiveRecord::Base

  def initialize(hour_id)
    super()
    self.hour_id = hour_id
    self.status = -2
    self.slug = SecureRandom.uuid.to_s
  end
end

像这样使用它

Timereg.new(1)
一切都很好。

我如何使用它

Timereg.create!

我无法弄清楚语法。我明白了:

ArgumentError: wrong number of arguments (2 for 1)

2 个答案:

答案 0 :(得分:4)

覆盖createinitialize方法是个坏主意。

您应该使用callbacks。您可以使用after_initialize挂钩来分配值。

答案 1 :(得分:0)

您需要添加块参数:

def initialize(hour_id, &block)
  super(nil, &block)
  ..
end

这就是ActiveRecord create!的样子:

# File activerecord/lib/active_record/persistence.rb, line 47
def create!(attributes = nil, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| create!(attr, &block) }
  else
    object = new(attributes, &block)
    object.save!
    object
  end
end

由于.new没有采用两个参数,create!失败。

但是作为@ kartikey-tanna said,首先修改初始化程序可能不是一个好主意。

考虑类似的事情:

def self.create_for_hour_id!(hour_id, attributes = nil)
  timereg = new(attributes)
  timereg.hour_id = hour_id
  yield timereg if block_given?
  timereg.save!
  timereg
end

并使用回调设置slug,status等:

before_validation :generate_slug

private
def generate_slug
  self.slug ||= SecureRandom.uuid.to_s
end