Skip to content

Commit

Permalink
Fix autosave association bug with ActiveStorage::Attachments
Browse files Browse the repository at this point in the history
Closes #37701.
  • Loading branch information
willtcarey authored and georgeclaghorn committed Apr 24, 2020
1 parent cbfbb2c commit 88c97f8
Show file tree
Hide file tree
Showing 6 changed files with 24 additions and 0 deletions.
4 changes: 4 additions & 0 deletions activestorage/lib/active_storage/attached/model.rb
Expand Up @@ -140,6 +140,10 @@ def attachment_changes #:nodoc:
@attachment_changes ||= {}
end

def changed_for_autosave? #:nodoc:
super || attachment_changes.any?
end

def reload(*) #:nodoc:
super.tap { @attachment_changes = nil }
end
Expand Down
8 changes: 8 additions & 0 deletions activestorage/test/database/create_groups_migration.rb
@@ -0,0 +1,8 @@
# frozen_string_literal: true

class ActiveStorageCreateGroups < ActiveRecord::Migration[6.0]
def change
create_table :groups do |t|
end
end
end
1 change: 1 addition & 0 deletions activestorage/test/database/create_users_migration.rb
Expand Up @@ -4,6 +4,7 @@ class ActiveStorageCreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.string :name
t.integer :group_id
end
end
end
2 changes: 2 additions & 0 deletions activestorage/test/database/setup.rb
@@ -1,7 +1,9 @@
# frozen_string_literal: true

require_relative "create_users_migration"
require_relative "create_groups_migration"

ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.connection.migration_context.migrate
ActiveStorageCreateUsers.migrate(:up)
ActiveStorageCreateGroups.migrate(:up)
8 changes: 8 additions & 0 deletions activestorage/test/models/attached/one_test.rb
Expand Up @@ -286,6 +286,14 @@ class ActiveStorage::OneAttachedTest < ActiveSupport::TestCase
assert_equal 2736, @user.avatar.metadata[:height]
end

test "updating an attachment as part of an autosave association" do
group = Group.create!(users: [@user])
@user.avatar = fixture_file_upload("racecar.jpg")
group.save!
@user.reload
assert @user.avatar.attached?
end

test "attaching an existing blob to a new record" do
User.new(name: "Jason").tap do |user|
user.avatar.attach create_blob(filename: "funky.jpg")
Expand Down
1 change: 1 addition & 0 deletions activestorage/test/test_helper.rb
Expand Up @@ -100,6 +100,7 @@ class User < ActiveRecord::Base

class Group < ActiveRecord::Base
has_one_attached :avatar
has_many :users, autosave: true
end

require_relative "../../tools/test_common"

0 comments on commit 88c97f8

Please sign in to comment.