• Archive
  • RSS
  • About Me
  • Résumé
  • github
  • twitter
  • Email

Dima Sabanin

Hey, I'm Dima Sabanin and I love programming.
I work on Beanstalk for Wildbit.

Too Cool for Internet Explorer

  • Note

    20th May 2008

    Rails tip if you use association proxy methods

    I like doing following in my code:
    class Blah < ActiveRecord::Base
      has_many :somethings
    end
    
    class Something < ActiveRecord::Base
      def self.for(person)
        find(:first, :conditions => {:owner_name => person})
      end
    end 
    
    # And then later
    @the_blah.somethings.for("dima") # => #<Something ....> 
    
    But I also can accidentally do this and break the expectation for the code, since I don’t have full conditions specified in the Something.for method:

    Something.for("dima")

    Right, no conditions from Blah will be applied and first Something with name “dima” will be returned. However, here’s a workaround I figured out, just write a Something.for method like this:
    class Something < ActiveRecord::Base
      def self.for(person)
        raise unless scoped?(:find)
        find(:first, :conditions => {:owner_name => person})
      end
    end
sdmitry at gmail.com

The Workshop — Мастерская скрапбукинга — Открытки ручной работы