首页 文章

我可以通过非关联其他表中包含的信息对一个表进行排序吗?

提问于
浏览
0

Rails 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 tabled包含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

上面给出的是nil,但这是我第一次尝试将SQL插入rails .

1 回答

  • 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
    

相关问题