John.Mazzucco
John.Mazzucco

Reputation: 289

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)

Upvotes: 1

Views: 42

Answers (2)

Andrey Deineko
Andrey Deineko

Reputation: 52377

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 })

Upvotes: 1

John.Mazzucco
John.Mazzucco

Reputation: 289

I was able to filter out the closed cards and the cards that belong to closed boards with this:

current_user.cards.to_a.delete_if { |card| card.board.closed == true || card.closed == true }

Upvotes: 0

Related Questions