marie
marie

Reputation: 231

How to write a query that retrives only object where association is not empty

I have 3 models :

 Product
 has_many :variants

 Variant
 has_many :stocks
 belongs_to :product

 Stock
 belongs_to :variant

I need to retrive the Variant where Stock is not empty

I tried this way but this does not work as expected... as it is empty it is not nil...

 @product.variants.includes(:stocks).where.not(stocks: nil)

Upvotes: 0

Views: 27

Answers (2)

Milind
Milind

Reputation: 5112

More simpler version of what you did.... using Has Many association reference

and in my Product Controller

def show
  @product_size_options = []    
  @product.variants.map do |var| 
     ##this will make sure that only persisted stocks comes out
      if var.stock_ids.size > 0
        @product_size_options  << var
      end
    end
 end

The above code can also be written in one line =>

@product.variants.map { |var| var if var.stock_ids.size > 0 }.compact.flatten

Hope it helps

Upvotes: 1

marie
marie

Reputation: 231

I did find a working solution in a different way:

In my Variant model

def has_stock
   self.stocks.empty? ? false : true
end

and in my Product Controller

def show
  @product_size_options = []    
  @product.variants.map do |var| 
      if var.has_stock == true
        @product_size_options  << var
      end
    end
 end

Upvotes: 0

Related Questions