Specifically, let's assume that we have two sensible models:
TieDyeCentipede
, which has_many :legs
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With