Skip to content

Instantly share code, notes, and snippets.

@joshmcarthur
Created August 19, 2018 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshmcarthur/fda80a4b138e393608d9ad43aa093be1 to your computer and use it in GitHub Desktop.
Save joshmcarthur/fda80a4b138e393608d9ad43aa093be1 to your computer and use it in GitHub Desktop.
Self-referential, unidirectional has many through association
require "bundler/inline"
gemfile do
source "https://rubygems.org"
gem "activerecord"
gem "sqlite3"
gem "minitest"
end
require "minitest/autorun"
require "active_record"
ActiveRecord::Base.establish_connection(adapter: :sqlite3, database: "test.db")
ActiveRecord::Schema.define do
self.verbose = true # or false
create_table(:follows, force: true) do |t|
t.integer :source_id, null: false
t.integer :destination_id, null: false
end
create_table(:users, force: true)
add_index :follows, [:source_id, :destination_id], unique: true
end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
class Follow < ApplicationRecord
belongs_to :source, class_name: "User", inverse_of: :follows
belongs_to :destination, class_name: "User", inverse_of: false
end
class User < ApplicationRecord
has_many :follows, inverse_of: :source, foreign_key: :source_id
has_many :followings, through: :follows, source: :destination
end
class AssociationTest < Minitest::Test
def test_user_resolves_followings
user1 = User.create!
user2 = User.create!
Follow.create!(source: user1, destination: user2)
assert_equal user1.followings.first, user2
end
end
# To test:
# `ruby playground.rb`
# To run:
# `irb`
# => load "./playground.rb"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment