【问题标题】:Getting a model's children获得模特的孩子
【发布时间】:2013-11-28 00:39:57
【问题描述】:

如果我有一个模型,即。用户和每个用户 has_many :animals,我如何获取所有特定用户动物集合的检索列表?

我想做这样的事情:

a = User.where(:last_name => 'Statham').animals

并且有一个 Animal 对象的列表。我想我错过了一些琐碎而简单的事情。

【问题讨论】:

    标签: ruby-on-rails activerecord rails-activerecord


    【解决方案1】:

    试试这个:

    Animal.where(user_id: User.where(last_name: "Statham"))
    

    【讨论】:

      【解决方案2】:

      是的,简单就是正确的。你在那里有很多用户,所以你需要遍历他们。

      stathams = User.where(:last_name => 'Statham')
      stathams.each { |statham| statham.animals }
      

      如果你想避免重复:

      animals = []
      stathams = User.where(:last_name => 'Statham')
      stathams.each { |statham| animals << statham.animals }
      animals.uniq!
      

      【讨论】:

      • 我明白,对于第一个用户 - 但是如果我想要属于多个用户的所有动物怎么办? IE。我想要一个属于名字为“约翰”的用户的动物列表。
      猜你喜欢
      • 2023-02-25
      • 2018-04-28
      • 2013-01-31
      • 2012-03-07
      • 2011-08-05
      • 2011-06-01
      • 2013-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多