Guest User

Untitled

a guest
Feb 20th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. =begin
  2.  
  3. = Find Those With =
  4.  
  5. A macro method for defining named_scopes for has_many owners.
  6.  
  7. USAGE
  8.  
  9. Find only those posts with comments:
  10.  
  11. class Post < ActiveRecord::Base
  12. has_many :comments
  13.  
  14. finds_those_with :comments
  15. end
  16.  
  17. Post.with_comments
  18.  
  19. DISCLAIMER
  20.  
  21. I don't know what the crap I'm doing with SQL.
  22.  
  23. =end
  24. ActiveRecord::Base.class_eval do
  25. def self.finds_those_with(name, options={})
  26. options[:using] ||= "with_#{name}"
  27. options[:model] ||= name.to_s.classify.constantize
  28. named_scope options[:using].to_sym,
  29. :include => name,
  30. :select => "#{table_name}.*",
  31. :conditions => "#{options[:model].table_name}.id IS NOT NULL"
  32. end
  33. end
Add Comment
Please, Sign In to add comment