Here is the question, I have a customer and address model as follows:
class Customer < ActiveRecord::Base
has_one :address, as: :addressable
end
class Address < ActiveRecord::Base
belongs_to :addressable, polymorphic: true
end
I have a customer form with the render address information, for example:
# customers/form
= f.input :name
...
# render form/address
= f.input :apto
= f.input :city
= f.input :references
What I am looking for is to validate the address fields in the customer form, in such a way that if the user does not enter any value then it prevents its creation or update
pdd: The address entity is polymorphic and I can use it in any relationship. But I don't know how to validate its fields when I use it in the form of other relations
If you could help me I would be grateful and thank you very much for taking the time to read me.
UPDATE 22/12/2022
I would like to specifically validate the address fields (apto, city, reference) that are in customers only and not in others entities
Since any other entity can use address and in those entities the fields must be without validation
many thanks to @max who recommended validates_associates, however it validates all addresses
CodePudding user response:
Maybe you are looking for:
validate :validate_fields, if: -> { addressable_type == 'Customer' }