Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rails 3 have find_by association magic?

Specifically, let's assume that we have two sensible models:

  1. TieDyeCentipede, which has_many :legs
  2. Leg, which has a :color attribute.

Being a TieDyeCentipede, no two legs are ever the same color. In fact, a particular leg's color is unique among all of the legs of all of our TieDyeCentipedes.

Based on that uniqueness, we want to find a particular Centipede by a particular color of leg -- let's say :deep_sky_blue.

I could do something like:

critter = Leg.find_by_color(:deep_sky_blue).tie_dye_centipede

However, is there a find_by_* method on the TieDyeCentipede class that I could use as well?

like image 499
ClosureCowboy Avatar asked Jan 26 '11 04:01

ClosureCowboy


1 Answers

No magic:

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

Some magic:

def self.find_by_leg_color(color)
  TieDyeCentipede.joins(:legs).where(:legs => {:color => color}).first
end
like image 159
ahmed Avatar answered Oct 15 '22 12:10

ahmed