Skip to content

Instantly share code, notes, and snippets.

@hyoshida
Forked from su10/hash_for_includes_all_masters.rb
Last active August 29, 2015 14:01
Show Gist options
  • Save hyoshida/3598fb0232403a0cb526 to your computer and use it in GitHub Desktop.
Save hyoshida/3598fb0232403a0cb526 to your computer and use it in GitHub Desktop.

HOW TO USE

  1. put these codes in Ruby on Rails application.
module AssociationsForIncludes
  # As follows or paste codes here.
  #require 'associations_for_includes'
end

ActiveRecord::Base.send(:extend, AssociationsForIncludes)
  1. call the method from ActiveRecord model.
Hoge.associations_for_includes
def associations_for_includes(recursive: true, except: nil, _breadcrumb: [])
_breadcrumb << self.class_name
self.reflect_on_all_associations.map do |association_reflection|
association_name = association_reflection.name
class_name = association_reflection.class_name
next if _breadcrumb.include?(class_name)
next if association_reflection.options.has_key?(:polymorphic)
case except
when Regexp
next if class_name =~ except
when String, Hash
next if class_name == except.to_s
end
# when depth:1
next association_name unless recursive
# when recursive
recursive_associations = class_name.constantize.associations_for_includes(recursive: recursive, except: except, _breadcrumb: _breadcrumb)
if recursive_associations.any?
{ association_name => recursive_associations }
else
association_name
end
end.compact
end
@hyoshida
Copy link
Author

不正な関連があるとエラーが出るので、それを検知するためにも使える

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment