Last active
April 22, 2023 08:31
-
-
Save usutani/00d7e77bafdf692918bd1162a31c645d to your computer and use it in GitHub Desktop.
Rails: has_many distinct through: source: の習作 https://note.com/usutani/n/n741bd5112e43
This file contains 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 | |
# Rails: 私の好きなコード(5)永続化とロジックを絶妙にブレンドするActive Record(翻訳) | |
# https://techracho.bpsinc.jp/hachi8833/2023_04_18/127103 | |
# Topic | |
# has_many :entry_creators, -> { distinct }, through: :entries, source: :creator | |
# | |
# https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_record_gem.rb | |
# Rename: Post(posts) => Topic(topics), Comment(comments) => Entry(entries) | |
# New: Creator(creators) | |
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", "~> 7.0.0" | |
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 :topics, force: true do |t| | |
end | |
create_table :entries, force: true do |t| | |
t.integer :topic_id | |
t.integer :creator_id | |
end | |
create_table :creators, force: true do |t| | |
end | |
end | |
class Topic < ActiveRecord::Base | |
has_many :entries | |
has_many :entry_creators, -> { distinct }, through: :entries, source: :creator | |
end | |
class Entry < ActiveRecord::Base | |
belongs_to :topic | |
belongs_to :creator | |
end | |
class Creator < ActiveRecord::Base | |
has_many :entries | |
end | |
class BugTest < Minitest::Test | |
def test_association_stuff | |
topic = Topic.create! | |
creator = Creator.create! | |
Entry.create! topic: topic, creator: creator | |
Entry.create! topic: topic, creator: creator | |
assert_equal 2, topic.entries.count | |
assert_equal 1, topic.entry_creators.count | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment