Rails update attributes not validating
(Wroclaw or Remote) Ready to join a a fast-paced, high-growth technology company and help us to improve our best–in-industry solutions.Active Model validations in Rails are awesome, but what happens when your UI doesn’t exactly match your data model?Rails provide a wide range of options for creating rich forms for your models.This can be a simple form for one object, or the form for many related objects. If you are not familiar with such terms as form_for or accepts_nested_attributes_for, I strongly recommend taking a look at this article Complex Rails Forms with Nested Attributes, written by Xavier Shay, which will show your how you can create complex forms with Rails.Suppose, we have a model called The problem here is that accepts_nested_attributes_for call destroy for child objects AFTER validation of the parent object. Of course, later, when the user will try to edit a company, he/she will get an error - “Company should have at least one office.”.), and it actually works, but again, it does not take into account the fact that some of the records may be marked for destruction. To sort out the problem, we need to understand what # accepts_nested_attributes_for generates for us this method def offices_attributes=(attributes) # @note the name of the method to call may vary depending on the type of association # @see https://github.com/rails/rails/blob/master/activerecord/lib/active_record/nested_attributes.rb#L285 assign_nested_attributes_for_collection_association(:offices, attributes, mass_assignment_options) end def assign_nested_attributes_for_collection_association ... call_reject_if(association_name, attributes) # if the record passed # update a record with the attributes or marks it for destruction assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy], assignment_opts) end ...
One approach to handling implementing this is to rely solely on client validations, but I .
do validates :pet_type, presence: true, inclusion: validates :dog_type, presence: true, if: "pet_type === 'dog'" validates :cat_type, presence: true, if: "pet_type === 'cat'" endwith_options if: :pet_friendly?
do validates :pet_type, presence: true, inclusion: validates :dog_type, presence: true, unless: "pet_type === 'cat'" validates :cat_type, presence: true, unless: "pet_type === 'dog'" endwhich gives me 2 conditions or a validation in a pretty clean and understandable way.
Then we’ll need more information such as bedrooms, bathrooms, parking spaces, yard, jacuzzi, etc…
We don’t want to put this on one giant form because giant forms are a turn-off.
This is incredibly powerful and is extremely helpful when the state or your model depends on the presence of certain data.