0

我有一个带有一些相关日期字段的模型。

def started_at_date=(value)
  @started_at_date = value
end

def completed_at_date=(value)
  @completed_at_date = value
end

...

吸气剂是通过处理的method_missing,效果很好。

def method_missing(method, *args, &block)
  if method =~ /^local_(.+)$/
    local_time_for_event($1)
  elsif method =~ /^((.+)_at)_date$/
    self.send :date, $1
  elsif method =~ /^((.+)_at)_time$/
    self.send :time, $1
  else
    super
  end
end

def date(type)
  return self.instance_variable_get("@#{type.to_s}_date") if self.instance_variable_get("@#{type.to_s}_date")
  if self.send type.to_sym
    self.send(type.to_sym).in_time_zone(eventable.time_zone).to_date.to_s
  end
end

...

我想动态添加设置器,但我不确定如何以避免ActiveRecord::UnknownAttributeErrors.

4

3 回答 3

2

我认为这会起作用:

def method_missing(method, *args, &block)
  super unless method =~ /_date$/
  class_eval { attr_accessor method }
  super
end
于 2012-05-26T15:06:24.317 回答
1

你可以只使用虚拟属性吗?

Class Whatever < ApplicationModel

  attr_accessor :started_at_date
  attr_accessor :completed_at_date

  #if you want to include these attributes in mass-assignment
  attr_accessible :started_at_date
  attr_accessible :completed_at_date


end

当您需要稍后访问属性而不是调用 @started_at_date 时,您将调用 self.started_at_date 等。

于 2012-05-26T14:44:09.490 回答
1

如果我理解正确,请尝试:

  # in SomeModel
  def self.new_setter(setter_name, &block)
      define_method("#{setter_name}=", &block)
      attr_accessible setter_name
  end

用法:

 SomeModel.new_setter(:blah) {|val| self.id = val }

 SomeModel.new(blah: 5) # => SomeModel's instance with id=5
 # or
 @sm = SomeModel.new
 @sm.blah = 5
于 2012-05-26T15:14:22.963 回答