railsmonk RSS

Hey, I'm Dima Sabanin and I love programming and I've been doing this since I was 10 years old. For the last 3 years I work with Rails.

I study Zen, I have a family with a small kid. This is my brain dump.

Email: sdmitry@gmail.com




Recommend Me

Archive

May
20th
Tue
permalink
Google AdSense made no sense for me. Turned it off
permalink

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
May
1st
Thu
permalink
Apr
19th
Sat
permalink
Apr
1st
Tue
permalink
Mar
15th
Sat
permalink
Mar
14th
Fri
permalink
Mar
13th
Thu
permalink
Mar
8th
Sat
permalink
Mar
5th
Wed
permalink