开发者

Rails 3 Validation on a group of fields

I have a model with a whole bunch of fields. Not all fields are used based on the user selecting a certain type of form. I have around 6 different types of forms so a field may be used on 4 of them.

Is there a way to group validation based on a element ie?

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

I will be doing client side validation but I obviously will need server side as well to make sure they have submitted good data.

Any suggestions how this can be done ?

I'm using Rails3 wit开发者_如何学Ch Mongoid 2.0

Thanks in advance!


Something like this?

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) }


I see a problem with the model class having to have intimate knowledge of the views involved. If the forms in the views were named differently, the solution won't work. You will want to use "validation groups" like that used in ASP.NET. You could do some search on that and either find a similar solution for Rails or roll your own. Maybe this one will help: https://github.com/akira/validationgroup

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜