我喜欢在我的Rails应用程序中使用composition_of,它可以帮助我从原始数据库数据中构建漂亮的问题空间对象。

但是,我有一个问题,最好是使用自动魔术ActiveRecord方式验证它们的最佳方法是什么?

有时候验证原始数据就足够了,但是对象通常太复杂了,您想向用户报告有意义的信息(靠近组成对象)。

我发现了这一点:http://www.stephenchu.com/2008/05/rails-composedof-validation.html,但它看起来并不优雅或不像Rails。

最佳答案

您为什么不能执行此操作(来自我的一个应用程序的示例):

composed_of :cents_cost_amount,
            :class_name => "Money",
            :mapping => [%w(cents_cost_amount cents), %w(currency currency_as_string)],
            :constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) },
            :converter => Proc.new { |value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError, "Can't convert #{value.class} to Money") }

validates :cents_cost_amount,
          :numericality => {:greater_than_or_equal_to => 0,
                            :less_than_or_equal_to => 1000000,
                            :message => "Only amounts in the range 0 to 10000.00 are allowed."  }


没有特定的示例,很难让您对问题有更多的了解。

07-26 09:35
查看更多