【问题标题】:Rails finding from nested recordsRails 从嵌套记录中查找
【发布时间】:2021-06-17 11:57:31
【问题描述】:

product.rb

  class Product < ApplicationRecord
    has_many :product_items
  end

product_item.rb

 class ProductItem < ApplicationRecord
    belongs_to :product
    has_many :prices
  end

price.rb

class Price < ApplicationRecord
   belongs_to :product_item
end

现在价格表有一个名为otc的列,它存储产品项目的一次性成本,产品项目可以有多个价格。

目标:产品有很多产品,但我需要找到一个最低成本的产品项目(比如default_product_item)。需要从价格表中为最低 otc 的产品选择产品项目(以及 otc)。

我正在使用 ruby​​ 3.0.1、rails 6.1.3.2、数据库、Postgres。

【问题讨论】:

  • 您要退货还是退货?
  • 希望以最低价格获得产品。

标签: ruby-on-rails postgresql


【解决方案1】:
product_items = ProductItem.where(product: @product).joins(:prices).select("product_items.*", "MIN(prices.otc) as min_price").group('product_items.id').order('min_price').first

这应该返回类似的 SQL

SELECT product_items.*, MIN(prices.otc) as min_price
FROM product_items
INNER JOIN 
prices
WHERE product_items.product_id = 6
ON product_items.id = prices.product_item_id
GROUP BY product_items.id
ORDER BY min_price 
LIMIT 1

【讨论】:

  • 试过这个但遇到了以下错误。由 PG::UndefinedTable 引起:错误:缺少表“product_items”的 FROM 子句条目
  • 我解决了这个问题。在 product.rb 中添加关系为 has_many :prices, through: :product_items,现在 price.order(:otc).first from product 会给我最低价格的价格,从这里我得到 product_item
猜你喜欢
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 2016-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多