Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
validate presence of polymorphic object when accepting nested attributes?
class Business < ActiveRecord::Base
has_one :location, as: :locatable
accepts_nested_attributes_for :location, allow_destroy: true, reject_if: -> (attributes) { attributes['address'].blank? }
class Location < ActiveRecord::Base
belongs_to :locatable, polymorphic: true
validates_presence_of :locatable, unless: ->(location) { location.locatable_type.present? }

brkattk commented Feb 29, 2012

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.


brkattk commented Mar 1, 2012

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.


brkattk commented Sep 25, 2012

Unfortunately, inverse_of will not work for polymorphic associations -

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment