如果所有孩子都尊重某个条件,ActiveRecord会找到Parent

时间:2018-02-09 17:07:21

标签: ruby-on-rails postgresql activerecord

availables_locales是一个postgres数组,其中包含一个语言环境列表。我想要做的就是让所有的房间让它的每个孩子都boxes尊重这个条件。 (包含语言环境)

这就是我所得到的,但它只是作为,至少一个,而不是每个。

class Room 
  has_many :boxes

  scope :available, -> { joins(:boxes).where('boxes.available_locales @> ?', "{#{I18n.locale}}") }
end

1 个答案:

答案 0 :(得分:0)

如果任何房间至少有一个Box,请尝试反向条件,如:

class Box < ApplicationRecord
  belongs_to :room

  scope :not_locale_rooms do
    select(:room_id)
      .where.not('boxes.available_locales @> ?', "{#{I18n.locale}}")
  end
end

class Room < ApplicationRecord
  has_many :boxes

  scope :with_all_locale_boxes, ->{ where.not(id: Box.not_locale_rooms) }
end

否则,您必须再向where添加with_all_locale_boxes以确保Room有一个方框。

相关问题