开发者

How to validate quantity of nested attributes with a minimum?

Two models: Field and Values. Value is nested to Field using accepts_nested_attributes_for

A Field can have many Values. The field has the attribute input_type that is a enum and can be :text, :checkbox, :radio ou :select. The values are the options displayed for this Field, so, if field.input_type is radio or select, there is no logic in using just one value to the field.

Using validation on Field, how can I prevent the i开发者_JS百科nsertion of a Field with only one Value?

Thanks


I'm not 100% clear on your question, but if I understand you correctly, you want to prevent an instance of the Field model from being saved if it has only one associated Value?

class Field < ActiveRecord::Base
  include ActiveModel::Validations
  has_many :values
  validates :values, :presence_of_multiple => true
end

class PresenceOfMultiple < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    record.errors[attribute] << "must have more than one." unless \
      value.exists? && value.count > 1
  end
end

This would be the most Rails-ish way to do it as far as I know, but you could also write it as a model method that gets called in the before_validation callback. There's actually a number of ways to do this sort of thing.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜