Skip to content

Instantly share code, notes, and snippets.

@aergonaut
Created July 15, 2020 16:26
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 aergonaut/eed8db8b6bdd2646cd78ec9048d78cbe to your computer and use it in GitHub Desktop.
Save aergonaut/eed8db8b6bdd2646cd78ec9048d78cbe to your computer and use it in GitHub Desktop.
require "bundler/inline"
gemfile(true) do
gem "activerecord", "~> 5.2.0"
gem "sqlite3"
end
require "active_record"
ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:"
ActiveRecord::Schema.define do
create_table :users, force: true do |t|
t.string :name
end
create_table :posts, force: true do |t|
t.belongs_to :user
end
create_table :comments, force: true do |t|
t.belongs_to :post
t.belongs_to :user
end
create_table :reactions, force: true do |t|
t.belongs_to :post
t.belongs_to :user
end
end
class User < ActiveRecord::Base
has_many :posts
has_many :comments
has_many :reactions
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
has_many :reactions
end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
class Reaction < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
# Goal: query all Posts where a commenter was named FOO or a reacter was named BAR
arel_sql =
Post.joins(comments: :user, reactions: :user)
.where(Post._reflections["comments"].klass._reflections["user"].klass.arel_table[:name].eq("FOO"))
.where(Post._reflections["reactions"].klass._reflections["user"].klass.arel_table[:name].eq("BAR"))
.to_sql
puts arel_sql
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment