Created
June 7, 2012 10:51
-
-
Save ichi/2888183 to your computer and use it in GitHub Desktop.
unscopedなassociationなやつ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/initializers/active_record.rb | |
class ActiveRecord::Base | |
class << self | |
# 参考: http://techracho.bpsinc.jp/baba/2011_11_28/4729 | |
def define_unscoped_model(name, model, options = {}) | |
model_name = if options[:class_name] | |
options[:class_name].to_s | |
else | |
(options[:source] || model).to_s.classify | |
end | |
define_method "unscoped_#{model}" do | |
model_name.constantize.unscoped do | |
relation = __send__(model) | |
if name == 'belongs_to' | |
relation | |
else | |
relation.order | |
end | |
end | |
end | |
end | |
private :define_unscoped_model | |
%w(belongs_to has_many has_and_belongs_to_many).each do |name| | |
new_method = "#{name}_with_unscoped" | |
old_method = "#{name}_without_unscoped" | |
define_method new_method do |model, options = {}| | |
__send__(old_method, model, options) | |
define_unscoped_model(name, model, options) unless options[:polymorphic] #とりあえずpolymorphic無視 | |
end | |
alias_method_chain name, :unscoped unless method_defined? old_method | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment