k10a
k10a

Reputation: 1087

How to exclude items have already chosen

I'm working on the application which users can choose items but they can't choose ones have already been chosen.

BoardItem has board_id and item_id. An item that was already chosen should not be included in the selected collection. Item and board have board items.

@board = Board.find(params[:id])
@chosen = BoardItem.select{ |board_item| board_item.board === @board }
@choosing = Item.select{ |item| item.board_items.each do |board_item|
                             @chosen.exclude?(board_item)
                            end }

Please help me.

Upvotes: 1

Views: 51

Answers (2)

Thounder
Thounder

Reputation: 325

You should be able to do it with a simple query such as

Item.includes(:board).where(boards: {id: nil })

You may have to tweak a bit the syntax regarding your models.

The goal is to load all items expect the ones with an existing relation

Upvotes: 1

Md. Farhan Memon
Md. Farhan Memon

Reputation: 6121

You can exclude selected IDs in the where query as:

@board = Board.find(params[:id])
selected_item_ids = @board.board_items.pluck(:item_id)
@unselected_items = Item.where.not(id: selected_item_ids)

Upvotes: 2

Related Questions