Scott Swezey The more I learn, the less I know.

20Jun/100

iterate through each child association of a active record class

I came across this today while trying to find a better way to deal with error messages in rails. IMHO, it is genius and just what I was looking for.Original code came from: http://snippets.dzone.com/posts/show/2892

class ActiveRecord::Base
  def each_child
    self.class.reflect_on_all_associations.each do |assoc|
      case assoc.macro
        when :has_many then send(assoc.name).each { |child| yield child }
        when :has_one then yield send(assoc.name)
      end
    end
  end
end

Posted by Scott

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.