Does Rails 3 have the magic of the find_by association?

In particular, suppose we have two reasonable models:

  • TieDyeCentipede, which the has_many :legs
  • Legwhich has an attribute :color.

Being TieDyeCentipede, no two legs have the same color. In fact, the special color of the legs is unique among all the feet of all our TieDyeCentipedes.

Based on this uniqueness, we want to find a specific one with a Centipedespecial color of legs - say :deep_sky_blue.

I could do something like:

critter = Leg.find_by_color(:deep_sky_blue).tie_dye_centipede

However, is there a method find_by_*in the class TieDyeCentipedethat I could use?

+5
source share
2 answers

Without magic:

TieDyeCentipede.joins(:legs).where(:legs => {:color => 'deep_sky_blue'}).first

Magic:

def self.find_by_leg_color(color)
  TieDyeCentipede.joins(:legs).where(:legs => {:color => color}).first
end
+6

TieDyeCentipide.joins(:legs).where(:legs => {:color => :deep_sky_blue}).first

find_by_* - Pacecar, AR-.

+3

All Articles