Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

change autosave_association.rb so that association autosave can work #344

Merged
merged 1 commit into from Mar 20, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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