Last active
April 22, 2023 08:47
-
-
Save usutani/cab19d21e040b985d7229ce5b2a4ff4f to your computer and use it in GitHub Desktop.
Rails: has_many through: class_name: の習作 https://note.com/usutani/n/nb3d1fe9e085b
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 :blocked_trackers, through: :entries, class_name: "Entry::BlockedTracker" | |
# | |
# 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: Entry::BlockedTracker(entry_blocked_trackers) | |
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 | |
end | |
create_table :entry_blocked_trackers, force: true do |t| | |
t.integer :entry_id | |
end | |
end | |
class Topic < ActiveRecord::Base | |
has_many :entries | |
has_many :blocked_trackers, through: :entries, class_name: "Entry::BlockedTracker" | |
end | |
class Entry < ActiveRecord::Base | |
belongs_to :topic | |
has_many :blocked_trackers | |
end | |
class Entry::BlockedTracker < ActiveRecord::Base | |
belongs_to :entry | |
end | |
class BugTest < Minitest::Test | |
def test_association_stuff | |
topic = Topic.create! | |
entry = Entry.create! | |
topic.entries << entry | |
assert_equal 1, topic.entries.count | |
assert_equal 1, Entry.count | |
assert_equal topic.id, Entry.first.topic.id | |
blocked_tracker = Entry::BlockedTracker.create! | |
entry.blocked_trackers << blocked_tracker | |
assert_equal 1, Entry::BlockedTracker.count | |
assert_equal 1, topic.blocked_trackers.count | |
assert_equal blocked_tracker.id, topic.blocked_trackers.first.id | |
topic.entries << Entry.create! | |
assert_equal 2, topic.entries.count | |
assert_equal 2, Entry.count | |
assert_equal 1, topic.blocked_trackers.count | |
assert_equal blocked_tracker.id, topic.blocked_trackers.first.id | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment