Last active
March 15, 2019 16:33
-
-
Save abaldwin88/69a926253febc11cecf317aaa0c9ed44 to your computer and use it in GitHub Desktop.
Scoping within first_or_create callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require "bundler/inline" | |
gemfile(true) do | |
source "https://rubygems.org" | |
git_source(:github) { |repo| "https://github.com/#{repo}.git" } | |
# Activate the gem you are reporting the issue against. | |
gem "activerecord", "5.2.0" | |
gem "sqlite3", "~> 1.3.6" | |
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 :posts, force: true do |t| | |
end | |
create_table :comments, force: true do |t| | |
t.integer :post_id | |
t.string :content | |
end | |
end | |
class Post < ActiveRecord::Base | |
has_many :comments | |
end | |
class Comment < ActiveRecord::Base | |
belongs_to :post | |
after_save :access_comments_in_callback | |
def access_comments_in_callback | |
$sql = Post.first.comments.to_sql | |
end | |
end | |
class BugTest < Minitest::Test | |
def test_association_stuff | |
post = Post.create! | |
post.comments << Comment.create!(content: 'My Comment') | |
second_comment = post.comments.where(content: 'My Second Comment').first_or_initialize | |
second_comment.save! | |
assert_equal 'SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1', $sql | |
post.comments.where(content: 'My Third Comment').first_or_create! | |
assert_equal 'SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1', $sql | |
# Instead we get: SELECT "comments".* FROM "comments" WHERE "comments"."content" = 'My Third Comment' AND "comments"."post_id" = 1 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment