Skip to content

Commit

Permalink
Merge pull request #344 from ypxing/autosave_patch
Browse files Browse the repository at this point in the history
change autosave_association.rb so that association autosave can work
  • Loading branch information
cfis committed Mar 20, 2016
2 parents 9be245c + a6b1fbb commit 76fb5f2
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/composite_primary_keys.rb
Expand Up @@ -97,6 +97,7 @@
require 'composite_primary_keys/associations/collection_association'

require 'composite_primary_keys/dirty'
require 'composite_primary_keys/autosave_association'

require 'composite_primary_keys/attribute_methods/primary_key'
require 'composite_primary_keys/attribute_methods/dirty'
Expand Down
31 changes: 31 additions & 0 deletions lib/composite_primary_keys/autosave_association.rb
@@ -0,0 +1,31 @@
module ActiveRecord
module AutosaveAssociation
private
# Saves the associated record if it's new or <tt>:autosave</tt> is enabled.
#
# In addition, it will destroy the association if it was marked for destruction.
def save_belongs_to_association(reflection)
association = association_instance_get(reflection.name)
record = association && association.load_target
if record && !record.destroyed?
autosave = reflection.options[:autosave]

if autosave && record.marked_for_destruction?
self[reflection.foreign_key] = nil
record.destroy
elsif autosave != false
saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)

if association.updated?
# it will fail to use "#record.send(reflection.options[:primary_key] || :id)" for CPK
association_id = record.read_attribute(reflection.options[:primary_key] || :id)
self[reflection.foreign_key] = association_id
association.loaded!
end

saved if autosave
end
end
end
end
end
10 changes: 10 additions & 0 deletions test/test_associations.rb
Expand Up @@ -81,6 +81,16 @@ def test_has_one_association_is_not_cached_to_where_it_returns_the_wrong_one
refute_equal accounting_head, engineering_head
end

def test_association_with_composite_primary_key_can_be_autosaved
room = Room.new(dorm_id: 1000, room_id: 1001)
room_assignment = RoomAssignment.new(student_id: 1000)
room_assignment.room = room
room_assignment.save
room_assignment.reload
assert_equal(room_assignment.dorm_id, 1000)
assert_equal(room_assignment.room_id, 1001)
end

def test_has_one_association_primary_key_and_foreign_key_are_present
steve = employees(:steve)
steve_salary = steve.create_one_salary(year: "2015", month: "1")
Expand Down

0 comments on commit 76fb5f2

Please sign in to comment.