【问题标题】:Type safe Rails 3 Tableless Model键入安全 Rails 3 无表模型
【发布时间】:2012-09-10 15:29:11
【问题描述】:

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 无表模型中属性的类型是什么?

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-3 activemodel


【解决方案1】:

你应该看看ActiveAttr,它提供了这样的类型转换属性:

class Person
  include ActiveAttr::TypecastedAttributes
  attribute :age, :type => Integer
end

还有一个RailsCast about ActiveAttr

【讨论】:

    【解决方案2】:

    activerecord-tableless 宝石。它是创建无表 ActiveRecord 模型的宝石,因此它支持验证、关联、类型。

    您在问题中描述的方式不支持关联也不(如您所发现的)类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 2014-09-02
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 2012-02-25
      相关资源
      最近更新 更多