2

使用 Rails 3 和 ActiveModel,我无法使用 self. 获取基于 ActiveModel 的对象内的属性值的语法。

在下面的代码中,在 save 方法中,self.first_name 的计算结果为 nil,其中 @attributes[:first_name] 的计算结果为 'Firstname'(初始化对象时从控制器传入的值)。

在 ActiveRecord 中这似乎可以工作,但是在 ActiveModel 中构建相同的类时,它就不行了。您如何在基于 ActiveModel 的类中使用访问器来引用字段?

class Card
  include ActiveModel::Validations
  extend ActiveModel::Naming 
  include ActiveModel::Conversion
  include ActiveModel::Serialization
  include ActiveModel::Serializers::Xml

  validates_presence_of :first_name

  def initialize(attributes = {})
    @attributes = attributes
  end

  #DWT TODO we need to make sure that the attributes initialize the accessors properyl, and in the same way they would if this was ActiveRecord
  attr_accessor :attributes, :first_name

  def read_attribute_for_validation(key)
    @attributes[key]
  end

  #save to the web service
  def save
    Rails.logger.info "self vs attribute:\n\t#{self.first_name}\t#{@attributes["first_name"]}"
  end

  ...

end
4

2 回答 2

3

我想到了。作为对玛丽安的回答的评论,我提到的“hack”实际上正是 ActiveRecord 类的访问器是如何生成的。这是我所做的:

class MyModel
  include ActiveModel::AttributeMethods

  attribute_method_suffix  "="  # attr_writers
  attribute_method_suffix  ""   # attr_readers

  define_attribute_methods [:foo, :bar]

  # ActiveModel expects attributes to be stored in @attributes as a hash
  attr_reader :attributes

  private

  # simulate attribute writers from method_missing
  def attribute=(attr, value)
    @attributes[attr] = value
  end

  # simulate attribute readers from method_missing
  def attribute(attr)
    @attributes[attr]
  end
end

lib/active_record/attribute_methods/{read,write}.rb如果您查看 ActiveRecord 的源代码 ( ) ,您会看到相同的内容。

于 2011-11-19T18:23:51.520 回答
0

你需要ActiveModel::AttributeMethods那个

于 2011-09-30T18:22:37.280 回答