Skip to content

Instantly share code, notes, and snippets.

View tlowrimore's full-sized avatar

Tim Lowrimore tlowrimore

View GitHub Profile
@tlowrimore
tlowrimore / set_operations.rb
Created March 10, 2016 17:41
Extends the functionality set forth in union_scope.rb, to include EXCEPT and INTERSECT operations
module ActiveRecord
module Scopes
module SetOperations
extend ActiveSupport::Concern
class_methods do
def union_scope(*scopes)
apply_operation 'UNION', scopes
end
@tlowrimore
tlowrimore / union_scope.rb
Last active January 13, 2023 21:12
Unions multiple scopes on a model, and returns an instance of ActiveRecord::Relation.
module ActiveRecord::UnionScope
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def union_scope(*scopes)
id_column = "#{table_name}.#{primary_key}"
sub_query = scopes.map { |s| s.select(id_column).to_sql }.join(" UNION ")
where "#{id_column} IN (#{sub_query})"
@tlowrimore
tlowrimore / address_books_controller.rb
Last active February 22, 2023 20:24
Keeps your API lookin' good! No need for all that nested_attributes pollution in your request/response payloads
class V1::AddressBooksController < V1::BaseController
def create
@address_book = AddressBook.new address_book_params
unless @address_book.save
errors = @address_book.errors.to_hash(true)
render status: 422, json: { errors: errors }
end
end
private