我有一个名为product_variations
的表,并且此表具有很多products
。
当我进入Rails控制台时,我可以这样做:
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"
所以,这有效。但是,当我尝试使用where
在此处找到内容时,我得到了以下信息:
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
[请注意,当我尝试使用var.size
时,控制台会在数据库上进行另一次搜索,但是现在使用SELECT COUNT(*)
而不是仅使用SELECT
,并且输出为1
(而应为GG
,为什么?)。据我到目前为止所知,where
可以返回许多结果。那就是为什么它使用COUNT
?但是如何使用结果?在我正在使用的这个应用程序中,在product_variations
表格上,我只会与product_id
和sub_sku
进行一次匹配,因此我希望它返回此行,但无法弄清楚如何使用[ C0]为此。
您可以在位置之后使用.first。>
where
或使用find_by方法
var = ProductVariation.where(product_id: 1024, sub_sku: 10).first
将执行相同的操作