I was wondering if I can have a polymorphic association and also a presence validation
Let's say I have a business
model and an address
model, and address
is polymorphic
class Business< ActiveRecord::Base
has_one :address, as: :addressable
validates_presence_of :address
end
class Address< ActiveRecord::Base
belongs_to :addressable, polymorphic: true
end
Is it possible to have the validation validates_presence_of :address
? I am having issues when creating objects with this setup.
Let's say first I create a business object like this
b = Business.new(name: "Hello23")
b.address = Address.new(street: "House 43 BCD")
b.save!
This doesn't work. It gives an undefined method constantize for 0:Fixnum
and it makes sense to give an error, because when it tries to save the address to db it does not find an id of the addressable, since the business isn't yet saved and doesn't have an assigned id to it.
But it isn't possible from the other side around either - I can't save the business without having an address.
What is the best way to handle this kind of a situation?
****Apart from this what if I also want to have a validation on the address side like this**
validates_presence_of :addressable
I have been struggling with all this for about 2 days now. Let's see what ideas you people have ?**