这Railscast描述如何在 Rails 3 中设置无表模型,如下所示:
class Message
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name, :email, :content
validates_presence_of :name
validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
validates_length_of :content, :maximum => 500
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
它工作得很好,但它没有做的是让 Rails 知道属性的类型。这意味着虽然各种插件/库都可以工作,但它们往往会回退到有效地将属性视为“任何”类型。例如 to_xml 将它们列为“yaml”类型。
有没有办法告诉 Rails Tableless 模型中属性的类型是什么?
最佳答案
你应该看看ActiveAttr ,它提供了这样的类型转换属性:
class Person
include ActiveAttr::TypecastedAttributes
attribute :age, :type => Integer
end
关于ruby-on-rails - 类型安全的 Rails 3 无表模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8914835/