Rails 4 has_many 通过:从两个关联模型中过滤记录

Rails 4 has_many through: filtering records from both associated models

模特协会

class User < ActiveRecord::Base
  has_many :boards
  has_many :cards, through: :boards
end

class Board < ActiveRecord::Base
  belongs_to :user
  has_many :cards
end

class Card < ActiveRecord::Base
 belongs_to :board
end

检索记录

Card 和 Board 模型有一个名为 'closed' 的属性。 在检索属于 current_user.

的所有卡片时,我想过滤掉 'closed' 等于 true 的板和卡片


如果 board.closed == true,则过滤掉此板及其所有关联的卡片
if card.closed == true, 这张卡被过滤掉


这不起作用,但显示了我正在尝试做的事情:

current_user.cards.where(card.closed == false, card.board.closed == false)

我可以用这个过滤掉封闭的卡片和属于封闭板的卡片:

current_user.cards.to_a.delete_if { |card| card.board.closed == true || card.closed == true }
Card
  .joins(:board)
  .where(
    cards:  { closed: false },
    boards: { user_id: current_user.id, closed: false }
  )

或者,如果你坚持从current_user开始:

current_user
  .cards
  .joins(:board)
  .where(cards: { closed: false }, boards: { closed: false })