gpt4 book ai didi

ruby - ActiveModel 字段未映射到访问器

转载 作者:数据小太阳 更新时间:2023-10-29 08:53:12 28 4
gpt4 key购买 nike

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

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

在 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com