使用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

最佳答案

我想出来了。我提到的作为对Marian回答的评论的“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

如果查看activerecord的源代码(lib/active_record/attribute_methods/{read,write}.rb),也可以看到同样的情况。

关于ruby - ActiveModel字段未映射到访问器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7613574/

10-10 15:29