Search code examples
ruby-on-rails-4activerecordhas-many-throughmodel-associations

Rails 4 has_many through: filtering records from both associated models


MODEL ASSOCIATIONS

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

RETRIEVING RECORDS

The Card and the Board models have an attribute called 'closed'. I would like to filter out the boards and cards where 'closed' equals true, when retrieving all cards that belong to the current_user.

i.e.
if board.closed == true, this board and all of its associated cards are filtered out
if card.closed == true, this individual card is filtered out


This doesn't work, but is shows what I am trying to do:

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

Solution

  • Card
      .joins(:board)
      .where(
        cards:  { closed: false },
        boards: { user_id: current_user.id, closed: false }
      )
    

    Or, if you insist on starting from current_user:

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