0

I want to create a validation for the length of records of a nested attributes relation in rails 4. Due to the restriction on attr_accessible, I can't seem to access the nested fields attributes hash.

This is the validation I'm trying to create:

class Purchase
  MAX_PASSENGERS = 5

  validate :passengers_within_bounds

  accepts_nested_attributes_for :passengers

  private

  def passengers_within_bounds
    if passengers_attributes
      if (passengers.size + passengers_attributes.size) > MAX_PASSENGERS
        errors.add 'state', :max_passengers_exceeded
      end
    end
  end
end

In rails 3, I would use attr_accessible to access the passengers_attributes hash. But now, I don't know how to access it.

Do you guys know a way to access the nested attributes hash in a validation in rails 4?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
e3matheus
  • 2,112
  • 1
  • 20
  • 28

1 Answers1

1
validates :passengers, length: { maximum: 10 }
Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
  • I think he's going for an upper limit instead of a hard requirement: `validates :passengers, length: { maximum: 10 }` – aerook May 05 '14 at 21:17