Skip to content

Instantly share code, notes, and snippets.

@erkattak
Created February 29, 2012 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erkattak/1936811 to your computer and use it in GitHub Desktop.
Save erkattak/1936811 to your computer and use it in GitHub Desktop.
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? }
end
class Location < ActiveRecord::Base
belongs_to :locatable, polymorphic: true
validates_presence_of :locatable, unless: ->(location) { location.locatable_type.present? }
end
@erkattak
Copy link
Author

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.

@erkattak
Copy link
Author

erkattak 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.

@erkattak
Copy link
Author

Unfortunately, inverse_of will not work for polymorphic associations - http://guides.rubyonrails.org/association_basics.html#bi-directional-associations

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