Open sfcgeorge opened 6 years ago
Ok I found a way to work around but it's pretty gross:
class School < ApplicationRecord
has_many :subjects, class_name: "SchoolSubject", dependent: :destroy
validates_presence_of :name, :country, :from, :to, :city
after_save do
next unless subjects.empty?
errors.add(:subjects, "can't be blank")
raise ActiveRecord::Rollback
end
end
At first glance it seems like the key line has been elided:
We will have to re-enable that line and if it causes problems, find an intelligent solution.
I am figuring in some review of the code I thought: Hey this is unnecessary since it will hit the child record eventually and save that, which without the validates_presence_of works. Hopefully was just going for effeciency :-)
I have a model School that has_many :subjects, class_name: "SchoolSubject" and a validates_presence_of :subjects. It is impossible to save via Hyperloop! In the old Rails form using accept_nested_attributes_for it works fine because they are nested and Rails is smart to save them in such a way that the validation works. But I guess Hyperloop doesn't do this, or doesn't set up the association, or something, because I get the error that subject is missing 😬
Request:
Response:
Struggling to think of any workaround other than removing the validation. I had a similar issue with a maximum associated records validation, but I was able to move that to the associated record. That won't work here though as the only time you want the validation to run is when there isn't an associated, in which case the validation wouldn't be there to run.
Moving a maximum validation into the associated model works but won't work for minimum:
I think in Hypermesh the validations need to happen at the end of the transaction: save all records ignoring validations, then call valid? on all records that were saved and if any aren't then rollback the transaction.