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