Created
February 29, 2012 01:28
-
-
Save erkattak/1936811 to your computer and use it in GitHub Desktop.
validate presence of polymorphic object when accepting nested attributes?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Business < ActiveRecord::Base | |
has_one :location, as: :locatable | |
accepts_nested_attributes_for :location, allow_destroy: true, reject_if: -> (attributes) { attributes['address'].blank? } | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Location < ActiveRecord::Base | |
belongs_to :locatable, polymorphic: true | |
validates_presence_of :locatable, unless: ->(location) { location.locatable_type.present? } | |
end |
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.
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
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:
Even though this works when the locatable resource is a new and valid object, it's not 100% fool-proof.