此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知道属性的类型。这意味着,尽管各种插件/库可以工作,但它们倾向于将属性有效地视为“any”类型。例如,to_xml将它们列为'yaml‘类型。
有没有办法告诉Rails在无表模型中属性的类型?
发布于 2012-03-03 04:02:26
你应该看看ActiveAttr,它提供了如下类型转换的属性:
class Person
include ActiveAttr::TypecastedAttributes
attribute :age, :type => Integer
end还有一个RailsCast about ActiveAttr。
发布于 2012-09-07 20:40:06
这就是的宝石。它是创建无表ActiveRecord模型的宝石,因此它支持验证、关联、类型。
您在问题中描述的方式既不支持关联,也不支持(如您所发现的)类型。
https://stackoverflow.com/questions/8914835
复制相似问题