使用Rails 3和ActiveModel,我无法使用自我。语法来获取基于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
答案 0 :(得分:3)
我明白了。我提到的作为对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
),你可以看到同样的事情。
答案 1 :(得分:0)
您需要ActiveModel::AttributeMethods