2011-05-18 70 views
0

我有一大堆字段的模型。并非所有字段都是基于用户选择某种类型的表单而使用的。我有大约6种不同类型的表单,因此可以在其中的4个表单上使用一个字段。Rails 3对一组字段的验证

有没有一种方法来组合验证基于一个元素ie?

case xxx 
    when "form1" 
    validates :field1, :presence => true 
    when "form2" 
    validates :field1, :presence => true 
    when "form3" 
    validates :fiel2, :presence => true 
end 

我会做客户端验证,但我显然需要服务器端以确保他们已经提交了良好的数据。

任何建议如何做到这一点?

我正在使用Rails3与Mongoid 2.0

在此先感谢!

回答

1

这样的事情?

validates :field1, :presence => true, :if => Proc.new { |foo| %w{form1 form2}.include?(foo.xxx) } 
validates :field2, :presence => true, :if => Proc.new { |foo| %w{form1 form3}.include?(foo.xxx) } 
validates :field3, :presence => true, :if => Proc.new { |foo| %w{form2 form3}.include?(foo.xxx) } 
+0

这不会工作,因为foo是什么被验证。 foo不知道正在处理什么样的表单? – Lee 2011-05-18 12:02:03

+0

对不起,我假设xxx会是你的模型类的一个方法。由于不是,请将该位更改为%w {form1 form2} .include?(xxx)。也许真正的问题是xxx从哪里来?我之前使用过class_attribute来允许将模型设置为某种模式,但不确定这适用于您的情况。 – MacksMind 2011-05-18 15:57:29

1

我看到模型类有一个问题,不得不深入了解所涉及的视图。如果视图中的表单命名不同,解决方案将无法工作。您将需要使用ASP.NET中使用的“验证组”。你可以做一些搜索,找到一个类似Rails的解决方案或自己推出。也许这一个将帮助:https://github.com/akira/validationgroup