Ben Poon
Ben Poon

Reputation: 125

Dependent Validation on Multiple Objects Rails

I have three ActiveRecord objects that I need to validate as a whole and I'm not sure quite how to model or implement this yet.

The models are listed below with their dependencies/validations (pseudo-rails code):

When updating a campground record, it must be ensured that both the city and state are valid before attempting to update the campground record. If any step fails, I need to make sure nothing gets saved.

Would really love some help on this!

Upvotes: 2

Views: 934

Answers (1)

Jon
Jon

Reputation: 10908

First of all, it is not the responsibility of a Campground to verify the validity of the City or State it belongs to. Most likely, these will be existing records which aren't changing as you create or update a campground.

As for checking the association has been set, with Rails 5 any belongs_to association will automatically validate that an association has been set and that the record exists. With Rails 4 you can simply add a presence validation for your association within Campground:

belongs_to :city
validates :city, presence: true

For validating the uniqueness of a city name within a state you can simply use a scope:

belongs_to :state
validates :name, uniqueness: {scope: :state_id}

For everything else, it really is the responsibility of State to make sure it is valid at the point that it is created or updated. Unless some part of its validity comes from the collection of child objects it has relationships with? In which case you can add a validates_associated validation.

You can see the documentation for this validation here: http://edgeguides.rubyonrails.org/active_record_validations.html#validates-associated

Basically, within your State model you would add:

has_many :cities
validates_associated :cities

But this will only check that the children are valid when updating/creating a parent, not in the opposite direction.

Upvotes: 3

Related Questions