Question

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?

Was it helpful?

Solution

validates :passengers, length: { maximum: 10 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top