Skip to content

Commit 4c5e4ea

Browse files
authored
Fix autosave association bug with ActiveStorage::Attachments
Closes rails#37701.
1 parent 43d3b60 commit 4c5e4ea

File tree

6 files changed

+24
-0
lines changed

6 files changed

+24
-0
lines changed

activestorage/lib/active_storage/attached/model.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,10 @@ def attachment_changes #:nodoc:
179179
@attachment_changes ||= {}
180180
end
181181

182+
def changed_for_autosave? #:nodoc:
183+
super || attachment_changes.any?
184+
end
185+
182186
def reload(*) #:nodoc:
183187
super.tap { @attachment_changes = nil }
184188
end
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# frozen_string_literal: true
2+
3+
class ActiveStorageCreateGroups < ActiveRecord::Migration[6.0]
4+
def change
5+
create_table :groups do |t|
6+
end
7+
end
8+
end

activestorage/test/database/create_users_migration.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ class ActiveStorageCreateUsers < ActiveRecord::Migration[5.2]
44
def change
55
create_table :users do |t|
66
t.string :name
7+
t.integer :group_id
78
end
89
end
910
end

activestorage/test/database/setup.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
# frozen_string_literal: true
22

33
require_relative "create_users_migration"
4+
require_relative "create_groups_migration"
45

56
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
67
ActiveRecord::Base.connection.migration_context.migrate
78
ActiveStorageCreateUsers.migrate(:up)
9+
ActiveStorageCreateGroups.migrate(:up)

activestorage/test/models/attached/one_test.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,14 @@ def upload.open
319319
assert_equal 2736, @user.avatar.metadata[:height]
320320
end
321321

322+
test "updating an attachment as part of an autosave association" do
323+
group = Group.create!(users: [@user])
324+
@user.avatar = fixture_file_upload("racecar.jpg")
325+
group.save!
326+
@user.reload
327+
assert @user.avatar.attached?
328+
end
329+
322330
test "attaching an existing blob to a new record" do
323331
User.new(name: "Jason").tap do |user|
324332
user.avatar.attach create_blob(filename: "funky.jpg")

activestorage/test/test_helper.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ class User < ActiveRecord::Base
126126

127127
class Group < ActiveRecord::Base
128128
has_one_attached :avatar
129+
has_many :users, autosave: true
129130
end
130131

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

0 commit comments

Comments
 (0)