Rails 3是否有find_by关联魔法?

Clo*_*boy 5 ruby-on-rails associations ruby-on-rails-3

具体来说,我们假设我们有两个合理的模型:

  1. TieDyeCentipede, 哪一个 has_many :legs
  2. Leg,它有一个:color属性.

作为一个TieDyeCentipede,没有两条腿是相同的颜色.事实上,特定腿部的颜色在我们所有的腿部中都是独一无二的TieDyeCentipedes.

基于这种独特性,我们希望Centipede通过特定颜色的腿找到一个特定的 - 比方说:deep_sky_blue.

我可以这样做:

critter = Leg.find_by_color(:deep_sky_blue).tie_dye_centipede

但是,我可以使用find_by_*这个TieDyeCentipede类的方法吗?

小智 6

没魔法:

TieDyeCentipede.joins(:legs).where(:legs => {:color => 'deep_sky_blue'}).first
Run Code Online (Sandbox Code Playgroud)

一些魔力:

def self.find_by_leg_color(color)
  TieDyeCentipede.joins(:legs).where(:legs => {:color => color}).first
end
Run Code Online (Sandbox Code Playgroud)