Rails ActiveModel 属性类型
我在没有数据库后端的 Rails 3.1.1 项目中使用 ActiveModels。
我想知道如何将属性类型设置为字符串、布尔值、十进制。
根据我的理解,当使用数据库支持的 ActiveRecord 时,类型将直接从数据库元数据中获取。但是如果没有数据库,我在哪里定义属性类型呢?
编辑
我认为我的问题可以更好地提出,因为如何将模型元数据添加到由rest或JSONRPC2服务支持的模型中?
例如,我可以创建翻译器,确保将该模型编码为 JSON,知道哪个属性(ruby 中的属性,JSON 中的属性)是布尔值,哪个是数字——或者我可以尝试动态地找出它——但是似乎最好让我的模型用元数据注释这些属性/属性(在服务中)存储的类型。
接受的答案仍然不完全合适。尽管 Rails 模型不关心类型,但序列化方案 (JSON) 确实关心类型。在 JSON 中,数字和布尔值不应序列化为字符串。
I am using ActiveModels in a rails 3.1.1 project without a database backend.
I am wondering how I can set the types of attributes to String, Boolean, Decimal.
From my understanding, when using ActiveRecord backed by a database, the type would be taken directly from the database metadata. But with no database, where do I define the attribute types?
EDIT
I think my question could be asked better as, how do I add model metadata to a model that is backed by a rest or JSONRPC2 service?
For example, I could create translators that will make sure to encode that model into JSON, knowing which attribute (attribute in ruby, property in JSON) is Boolean and which is number -- or I could try to figure it out dynamically -- but it seems it would be best to have my model annotated with metadata on what type to store (in the service) these attribute/properties as.
The accepted answer still is not completely suitable. Even though Rails models do not care about types, the serialization scheme (JSON) DOES CARE ABOUT TYPES. In JSON Numbers and Boolean should not be serialized as Strings.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
attr_accessor
定义类的属性以供 ActiveModel 使用。不需要类型。请参阅关于“typed attr_accessor”的此问题。
You define the attributes of your class with
attr_accessor
to be use by ActiveModel. No type is required.See this question about "typed attr_accessor".