【问题标题】:Get all parent records where their first child has a specific property获取第一个孩子具有特定属性的所有父记录
【发布时间】:2014-03-06 16:51:26
【问题描述】:

我正在尝试创建一个 ActiveRecord 查询来检索其第一个孩子具有特定属性的所有父记录。

Parent has_many children
Child has_one parent

基本上我正在尝试做:

Parent.includes(:children).where('child.first.property = ?', 'something')

我怎样才能实现这样的目标?

【问题讨论】:

  • 它必须是第一个孩子吗?如果是这样,您要对孩子进行什么样的排序(即,首先按 id、日期等排序)?
  • 是的,它必须是第一个孩子。我想如果我不设置默认范围,订单将是'created_at asc'对吗?

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


【解决方案1】:

在您的代码中执行这些检查并担心以后的优化可能会更容易。

Parent.select { |p| p.children.order("created_at asc").first.property == "something" }

不过,这最终会为每个父母加载第一个孩子。另一种选择是首先加入具有该属性的子代以缩小父代的范围,然后执行上述相同的检查。

Parent.joins(:children).where(:property => "something").group("parents.id").select { |p| p.children.order("created_at asc").first.property == "something" } 

【讨论】:

    猜你喜欢
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 2020-11-14
    • 2020-06-06
    • 1970-01-01
    相关资源
    最近更新 更多