Skip to content

Instantly share code, notes, and snippets.

@laserlemon
Last active October 16, 2015 14:10
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 laserlemon/3f68d1901e30de54a4e1 to your computer and use it in GitHub Desktop.
Save laserlemon/3f68d1901e30de54a4e1 to your computer and use it in GitHub Desktop.
begin
require "active_record" # 4.2.4
require "ransack" # 1.6.6
require "sqlite3" # 1.3.11
rescue LoadError
warn "⚠️ Install the activerecord, ransack, and sqlite3 gems first."
exit
end
ActiveRecord::Base.establish_connection(
adapter: "sqlite3",
database: ":memory:"
)
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table :authors, force: true do |t|
end
create_table :authorships, force: true do |t|
t.integer :author_id
t.integer :post_id
end
create_table :comments, force: true do |t|
t.integer :post_id
t.datetime :created_at
end
create_table :posts, force: true do |t|
end
end
class Author < ActiveRecord::Base
has_many :authorships
has_many :posts, through: :authorships
end
class Authorship < ActiveRecord::Base
belongs_to :author
belongs_to :post
end
class Post < ActiveRecord::Base
has_many :authorships
has_many :authors, through: :authorships
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
author_1 = Author.create!(id: 1)
author_2 = Author.create!(id: 2)
post_1 = Post.create!(id: 1, authors: [author_1])
post_2 = Post.create!(id: 2, authors: [author_1])
post_3 = Post.create!(id: 3, authors: [author_2])
post_4 = Post.create!(id: 4, authors: [author_2])
Comment.create!(id: 1, post: post_1, created_at: 4.days.ago)
Comment.create!(id: 2, post: post_1, created_at: 2.days.ago)
Comment.create!(id: 3, post: post_2, created_at: 4.days.ago)
Comment.create!(id: 4, post: post_2, created_at: 2.days.ago)
Comment.create!(id: 5, post: post_3, created_at: 4.days.ago)
Comment.create!(id: 6, post: post_3, created_at: 2.days.ago)
Comment.create!(id: 7, post: post_4, created_at: 4.days.ago)
Comment.create!(id: 8, post: post_4, created_at: 2.days.ago)
relation = Post.
joins(:authors).
ransack(
# Swap the following two lines:
comments_created_at_gteq: 3.days.ago,
authors_id_eq: author_1.id,
).
result
begin
relation.to_a
rescue
puts "💣 Invalid SQL!"
else
puts "👍 All is well."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment