【问题标题】:finding childrenless models in Rails在 Rails 中寻找无子模型
【发布时间】:2015-06-26 19:21:26
【问题描述】:

我在模型中有一个自关联

belongs_to :parent, class_name: "Person"
has_many :children, foreign_key: :parent_id, class_name: "Person"

通过where(parent_id: nil)获取父母

如何获得所有没有孩子的人物模型作为范围?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord scope model-associations


    【解决方案1】:

    试试这个:

    scope :with_no_children, -> { includes(:children).where(children: { id: nil }) } # or children_items: { id: nil } if that's self-referencing association
    

    Reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 2015-06-23
      • 2010-09-25
      • 1970-01-01
      相关资源
      最近更新 更多