Prevent unnecessary database fetch for non-polymorphic relationships

This commit is contained in:
Matt Huggins 2015-02-04 09:11:27 -07:00
parent b16f7e0490
commit 4facf14f79
1 changed files with 12 additions and 7 deletions

View File

@ -373,15 +373,20 @@ module PaperTrail
def save_associations(version)
return unless PaperTrail::VersionAssociation.table_exists?
self.class.reflect_on_all_associations(:belongs_to).each do |assoc|
associated_record = send(assoc.name)
if associated_record && associated_record.class.paper_trail_enabled_for_model?
PaperTrail::VersionAssociation.create(
assoc_version_args = {
:version_id => version.id,
:foreign_key_name => assoc.foreign_key,
:foreign_key_id => associated_record.id
)
:foreign_key_name => assoc.foreign_key
}
if assoc.polymorphic?
if (associated_record = send(assoc.name)).class.paper_trail_enabled_for_model?
assoc_version_args.merge!(:foreign_key_id => associated_record.id)
end
elsif assoc.klass.paper_trail_enabled_for_model?
assoc_version_args.merge!(:foreign_key_id => send(assoc.foreign_key))
end
PaperTrail::VersionAssociation.create(assoc_version_args) if assoc_version_args.has_key?(:foreign_key_id)
end
end