我有一个看起来像这样的课程(简化)
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)
答案 0 :(得分:4)
覆盖create
或initialize
方法是个坏主意。
您应该使用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