Skip to content

Instantly share code, notes, and snippets.

@chsh
Created September 27, 2012 11:17
Show Gist options
  • Save chsh/3793510 to your computer and use it in GitHub Desktop.
Save chsh/3793510 to your computer and use it in GitHub Desktop.
validates polymorphic fields example...
class Foo < ActiveRecord::Base
belongs_to :target, polymorphic: true
# This validation will fail...
# validates :target, uniqueness: true
validates :target_type,
presence: {if: :target_id_present? }
validates :target_id,
presence: {if: :target_type_present? },
uniqueness: {allow_nil: true, scope: :target_type}
def target_type_present?
self[:target_type].present?
end
def target_id_present?
self[:target_id].present?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment