Skip to content

Instantly share code, notes, and snippets.

@pinzolo
Last active November 7, 2015 03:51
Show Gist options
  • Save pinzolo/126bae1ef5915d99dde2 to your computer and use it in GitHub Desktop.
Save pinzolo/126bae1ef5915d99dde2 to your computer and use it in GitHub Desktop.
Patch class for has_many options style in Rails3 and Rails4
module AssocOpts
extend ActiveSupport::Concern
module ClassMethods
def assoc_opts(options)
return [options] if Gem::Version.new(Rails.version) < Gem::Version.new('4.0.0')
order_option = options.delete(:order)
include_option = options.delete(:include)
if order_option && include_option
[Proc.new { order(order_option).includes(include_option) }, options]
elsif order_option
[Proc.new { order(order_option) }, options]
elsif include_option
[Proc.new { includes(include_option) }, options]
else
[options]
end
end
end
end
# Rails3 and Rails4
class Course < ActiveRecord::Base
include AssocOpts
has_many :students, *assoc_opts(order: :name, include: [:parents, :brothers], dependent: :destroy)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment