Search code examples
ruby-on-railsmodel-view-controllerwhere-clausehelper

Understanding the "where" and how to use it in Ruby on Rails


I have a table named product_variations, and this table has_many products.

When I go to Rails console, I can do this:

2.6.3 :036 > var = ProductVariation.first
  ProductVariation Load (0.2ms)  SELECT `product_variations`.* FROM `product_variations` ORDER BY `product_variations`.`id` ASC LIMIT 1
 => #<ProductVariation id: 16, product_id: 1024, color_id: 19, quantity: 1, size: "GG", sub_sku: 10, created_at: "2020-02-18 14:41:46", updated_at: "2020-02-18 14:41:46">
2.6.3 :037 > var.size
 => "GG"

So, that's working. But when I try to find something there using where, I got this intead:

2.6.3 :038 > var = ProductVariation.where(product_id: 1024, sub_sku: 10)
  ProductVariation Load (0.4ms)  SELECT `product_variations`.* FROM `product_variations` WHERE `product_variations`.`product_id` = 1024 AND `product_variations`.`sub_sku` = 10 LIMIT 11
 => #<ActiveRecord::Relation [#<ProductVariation id: 16, product_id: 1024, color_id: 19, quantity: 1, size: "GG", sub_sku: 10, created_at: "2020-02-18 14:41:46", updated_at: "2020-02-18 14:41:46">]>
2.6.3 :039 > var.size
   (0.2ms)  SELECT COUNT(*) FROM `product_variations` WHERE `product_variations`.`product_id` = 1024 AND `product_variations`.`sub_sku` = 10
 => 1

Note that when I try to use var.size, the console do another search at the database, but now using SELECT COUNT(*) instead of just SELECT, and the output is 1 (while should be GG, why?). For what I understood until now, where can return many results. Thats why it uses COUNT? But how can I use the result? In this app I'm working at, on the product_variations table I'll have only one single match with product_id and sub_sku so I want it to return this line, but can't figure out how to use where to do this.


Solution

  • you can use .first after the where

    var = ProductVariation.where(product_id: 1024, sub_sku: 10).first
    

    or use the find_by method

    var = ProductVariation.find_by(product_id: 1024, sub_sku: 10)
    

    which will do the same thing