Skip to content

Instantly share code, notes, and snippets.

# collection association e.g. has_many
owners = People.all
association_name = :photos
owners.each do |owner|
records = Array(whatever_you_want)
association = owner.association(association_name)
association.loaded!
class Photo < ActiveRecord::Base
scope :enabled, -> { where(photo: { enabled: true }) }
end
class Person < ActiveRecord::Base
has_one :display_photo, -> {
self.select_values = ["DISTINCT ON(photos.person_id) photos.*"]
instance_exec(&Photo.method(:enabled)).order('photos.person_id')
}, class_name: "Photo"
end
class Person < ActiveRecord::Base
has_many :photos
has_one :display_photo, -> {
self.select_values = ["DISTINCT ON(photos.person_id) photos.*"]
order('photos.person_id')
}, class_name: "Photo"
end
# Polymorphic association example
class Person < ActiveRecord::Base
class Person < ActiveRecord::Base
has_many :photos
has_one :display_photo, class_name: "Photo"
end
# WARNING: This only appears to work properly!
people = Person.all.includes(:display_photo)
people.each { |person| puts person.display_photo.id }
@mrbrdo
mrbrdo / gist:6562241
Last active December 23, 2015 01:39
JRuby process spawn with input, output, error redirection and env access
require 'java'
require 'stringio'
class ProcessBuilderWrapper
class Status
def initialize(status)
@status = status
end
def success?
@mrbrdo
mrbrdo / rails_group_count.rb
Last active June 6, 2018 11:29
Rails ActiveRecord / ActiveRelation grouped count as integer (sum of counts for each group). Tested on Postgres This can be used for Kaminari too (speeds up total_pages and total_count considerably).
module ActiveRecordGroupCount
extend ActiveSupport::Concern
module ExtensionMethods
def count(*args)
scope = except(:select).select("1")
query = "SELECT count(*) AS count_all FROM (#{scope.to_sql}) x"
ActiveRecord::Base.connection.execute(query).first.try(:[], "count_all").to_i
end
end
# Add RVM to PATH for scripting
[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # This loads RVM into a shell session.
__rvm_project_rvmrc
module Kernel
def companion(klass, &block)
klass.instance_eval(&block)
# or: klass.singleton_class.class_eval(&block)
end
end
class Cat
end
class Klass
def self.class_method ; end
end
class Klass
class << self
def class_method ; end
end
end
module Kernel
def with(object, &block)
object.instance_eval &block
end
end
# Simple way to use it
with "Ruby Rocks!" do
puts self
puts size