Topic: Polymorphic association with validation [Is it even possible ??]

I was wondering if I can have a polymorphic association and also a presence validation

Lets say I have a business model and an address model, 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 this possible to have the validation validates_presence_of :address, I am having issues when creating objects with this setup.

Let 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 a undefined method constantize for 0:Fixnum and it makes sense to give an error because when it tries to save address to db it does not find an id of the addressable since the business isnt yet saved and doesn't have an assigned id to it,

But it isn't also possible from the other side around, I can't save the business without having an address.

What can be 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. Lets see what ideas you people have ?**

Last edited by mabid (2012-05-21 15:40:18)

Re: Polymorphic association with validation [Is it even possible ??]

Try something like this:

class HasOneValidator < ActiveModel::Validator
  def validate(record)
    association = options.fetch(:association)
    message = options.fetch(:message, "You must have a #{association}")
    if association
      record.errors[association] << message unless record.send(association).present?
    end
    # 
  end
end

class Business < ActiveRecord::Base
  has_one : address
  validates_with HasOneValidator, association: :address
end