【问题标题】:Does Rails 3 have find_by association magic?Rails 3 有 find_by 关联魔法吗?
【发布时间】:2011-01-26 04:55:43
【问题描述】:

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

  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

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 associations


    【解决方案1】:

    没有魔法:

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

    一些魔法:

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

    【讨论】:

    • 老鼠!嗯,谢谢你的回答。我希望它有一些内置的魔力!
    【解决方案2】:

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

    对于find_by_* 方法或类似方法,我推荐Pacecar,它会为您的AR 模型生成许多有用的范围。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2011-12-15
      • 2015-12-15
      • 1970-01-01
      相关资源
      最近更新 更多