5

使用 rails 3.2.8 我有一个具有几个属性的模型设置

class MyModel < ActiveRecord::Base
  attr_accessible :foo, :bar
end

我有另一个使用上述作为委托类的类设置

class MyModelPresenter < DelegateClass(MyModel)
  def initialize(month, obj)
    @month = month
    super(obj)
  end

  def self.build(month, attributes = { })
    new(month, MyModel.new).tap do |p|
      p.attributes = attributes
    end
  end

  def attributes=(attributes)
    attributes.each { |k, v| send("#{k}=", v) }
  end
end

当我像这样创建一个新的 MyModelPresenter 时:

MyModelPresenter.build(Date.today, {:foo => 1})

我得到以下回复

NoMethodError: undefined method `foo=' for #<MyModel:0x1098f31a8>
    from /Users/me/.rbenv/versions/ree-1.8.7-2011.03/lib/ruby/gems/1.8/gems/activemodel-3.2.8/lib/active_model/attribute_methods.rb:404:in `method_missing'
    from /Users/me/.rbenv/versions/ree-1.8.7-2011.03/lib/ruby/gems/1.8/gems/activerecord-3.2.8/lib/active_record/attribute_methods.rb:149:in `method_missing'
    from /Users/me/dev/temp/app/presenters/my_model_presenter.rb:23:in `send'
    from /Users/me/dev/temp/app/presenters/my_model_presenter.rb:23:in `attributes='
    from /Users/me/dev/temp/app/presenters/my_model_presenter.rb:23:in `each'
    from /Users/me/dev/temp/app/presenters/my_model_presenter.rb:23:in `attributes='
    from /Users/me/dev/temp/app/presenters/my_model_presenter.rb:17:in `build'
    from /Users/me/dev/temp/app/presenters/my_model_presenter.rb:15:in `tap'
    from /Users/me/dev/temp/app/presenters/my_model_presenter.rb:15:in `build'

由于某种原因,模型上的数据库属性没有被定义(setter 或 getter)。在升级到 rails 3.2 之前,这一切都在 rails 3.1 应用程序中工作。

有谁知道为什么没有定义模型的属性方法?

4

1 回答 1

1

继承Delegator而不是使用DelegateClass解决了这个问题。这是最后一课的样子:

class MyModelPresenter < Delegator
  def initialize(month, obj)
    @month = month
    super(obj)
    @_sd_obj = obj
  end

  def __getobj__
    @_sd_obj
  end

  def self.build(month, attributes = { })
    new(month, MyModel.new).tap do |p|
      p.attributes = attributes
    end
  end

  def attributes=(attributes)
    attributes.each { |k, v| send("#{k}=", v) }
  end
end

如您所见,我还必须添加该def __getobj__方法。并@_sd_obj在初始化程序中设置为我委托的类的实例。

请参阅SimpleDelegator示例。

于 2012-11-08T23:07:37.523 回答