轨道5.1.6 Ruby 2.5.1
所以,我有三种模型:
class Product < ApplicationRecord
has_many :order_items, :dependent => :destroy
belongs_to :product_type
end
class ProductType < ApplicationRecord
has_many :products
end
class OrderItem < ApplicationRecord
belongs_to :order
belongs_to :product
end
我需要能够按产品类型对所有订单项进行排序的功能。按字母顺序,按仅在产品类型表中保存的产品类型的名称。列出的产品包含product_type_id。现在我正在按product_type_id进行排序,但这显然不是按字母顺序排列的。我试图了解如何根据不相关的表中包含的信息对order_items进行排序。也许这不可能吗?我怎样才能做到这一点?
scope :sort_by_product_info, -> {(
select("order_items.id, order_items.order_id, order_items.product_id,
order_items.quantity, products.id, products.name,
products.description, products.image, products.size,
products.product_type_id")
.joins(:product)
.order("products.product_type_id ASC, products.name ASC")
)}
我的想法是无法通过ActiveRecord做到这一点,我一直希望如此,而必须在此处使用原始SQL。
@products_w_type = <<-SQL
SELECT *
FROM order_items, products, product_types
JOIN products
ON order_items.product_id = products.id
JOIN product_types
ON products.product_type_id = product_types.id;
SQL
上面的无效,但这是我第一次尝试将SQL插入rails。
答案 0 :(得分:0)
以下作用域应该可以帮助您以所需的方式对其进行排序:
class OrderItem < ApplicationRecord
belongs_to :order
belongs_to :product
scope :sort_by_product_info, -> { joins(product: :product_type).
order('product_types.name ASC, products.name ASC') }
end
您还可以使用一个巧妙的技巧来检查基础SQL查询,方法是在控制台中使用.explain
方法:
OrderItem.sort_by_product_info.explain