Skip to content

Instantly share code, notes, and snippets.

@patbenatar
Created January 30, 2013 00:20
Show Gist options
  • Select an option

  • Save patbenatar/4669415 to your computer and use it in GitHub Desktop.

Select an option

Save patbenatar/4669415 to your computer and use it in GitHub Desktop.
Simple utility for working with polymorphic associations in ActiveRecord where queries.
module PolymorphicQueryHelper
class << self
def expand_polymorphic_hash(hash)
{}.tap do |expanded_hash|
for name, object in hash
expanded_hash.merge!({
"#{name}_id".to_sym => object.id,
"#{name}_type".to_sym => object.class.name
})
end
end
end
end
end
@patbenatar
Copy link
Author

For example:

MyModel.where(PolymorphicQueryHelper.expand_polymorphic_hash({
  polymorphic_association: OtherModel.first
}))

is expanded to

MyModel.where({
  polymorphic_association_id: OtherModel.first.id,
  polymorphic_assocation_type: OtherModel.class.name
})

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