Skip to content

Instantly share code, notes, and snippets.

@mri-dula
Last active April 11, 2018 12:15
Show Gist options
  • Save mri-dula/65a85c24364d61b93de9f255e9cba12c to your computer and use it in GitHub Desktop.
Save mri-dula/65a85c24364d61b93de9f255e9cba12c to your computer and use it in GitHub Desktop.
(#32476) has_many does not update on save if parent has not been changed
begin
require "bundler/inline"
rescue LoadError => e
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
raise e
end
gemfile(true) do
gem 'rails', '~> 5.0.0', '>= 5.0.0.1'
gem "sqlite3"
end
require "active_record"
require "minitest/autorun"
require "logger"
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :authors, force: true do |t|
t.integer :post_id
t.string :address, :length => 250
end
create_table :posts, force: true do |t|
t.string :content, :length => 250
end
create_table :likes, force: true do |t|
t.string :like_reason, :length => 250
end
create_table :likes_posts, force: true do |t|
t.integer :post_id
t.integer :like_id
end
end
class Author < ActiveRecord::Base
belongs_to :post
end
class Post < ActiveRecord::Base
has_and_belongs_to_many :likes
has_many :authors, :autosave => true
end
class Comment < ActiveRecord::Base
belongs_to :post
end
class Like < ActiveRecord::Base
has_and_belongs_to_many :posts, :autosave => true
end
class BugTest < Minitest::Test
def test_authors_address_must_save_if_there_is_change_in_post
post = Post.new(content: 'Some text.')
author = Author.create!(address: 'Mars')
post.authors << author
post.save!
like = Like.new(like_reason: 'Good content.')
post = Post.find(post.id)
post.content = 'Some edited content'
like.posts << post
author = post.authors[0]
author.address = 'Earth'
assert_equal true, author.changed?
assert_equal true, post.changed?
like.save!
author.reload
assert_equal author.address, 'Earth'
end
def test_authors_address_must_save_if_there_is_no_change_in_post
post = Post.new(content: 'Some text.')
author = Author.create!(address: 'Mars')
post.authors << author
post.save!
like = Like.new(like_reason: 'Good content.')
post = Post.find(post.id)
like.posts << post
author = post.authors[0]
author.address = 'Earth'
assert_equal true, author.changed?
assert_equal false, post.changed?
like.save!
author.reload
assert_equal author.address, 'Earth'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment