Skip to content

Instantly share code, notes, and snippets.

@allenwu1973
Created March 13, 2019 09:59
Show Gist options
  • Save allenwu1973/9dadb3cba64733501f49b40de9dc112b to your computer and use it in GitHub Desktop.
Save allenwu1973/9dadb3cba64733501f49b40de9dc112b to your computer and use it in GitHub Desktop.
inverse_of breaks association.build
# 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.2"
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 :users, force: true do |t|
end
create_table :ownerships, force: true do |t|
t.integer :user_id
t.string :resource_type
t.integer :resource_id
end
create_table :articles, force: true do |t|
end
end
class User < ActiveRecord::Base
has_many :ownerships
has_many :articles, through: :ownerships, source: :resource, source_type: "Article"
end
class Ownership < ActiveRecord::Base
belongs_to :user
belongs_to :resource, polymorphic: true, inverse_of: :ownerships
end
class Article < ActiveRecord::Base
has_many :ownerships, as: :resource
has_many :owners, through: :ownerships, source: :user
end
class BugTest < Minitest::Test
def test_association_stuff
user = User.create!
user.articles.build
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment