public
Created

validate presence of polymorphic object when accepting nested attributes?

  • Download Gist
business.rb
Ruby
1 2 3 4 5
class Business < ActiveRecord::Base
has_one :location, as: :locatable
 
accepts_nested_attributes_for :location, allow_destroy: true, reject_if: -> (attributes) { attributes['address'].blank? }
end
location.rb
Ruby
1 2 3 4 5
class Location < ActiveRecord::Base
belongs_to :locatable, polymorphic: true
 
validates_presence_of :locatable, unless: ->(location) { location.locatable_type.present? }
end

How do I make a new business with a nested location without getting a validation error?

I've read that in Rails 3 you should use :inverse_of => :business on the has_one, but that doesn't work - I think because locatable could be anything.

For now I'm doing the following:

validates_presence_of :locatable, unless: ->(obj) { obj.locatable_type.present? }

Even though this works when the locatable resource is a new and valid object, it's not 100% fool-proof.

After digging a bit deeper, I found that I may have been wrong in not defining inverse_of on both model relations. I'll test this as soon as I get a chance and post an update.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.