在Rails中按product_type.name订购产品

问题描述 投票:0回答:1

我有产品和产品类型

class ProductType < ApplicationRecord
    has_many :products
end

class Product < ApplicationRecord
    belongs_to :product_type

    def type_name
        self.product_type.name
    end
end

我可以在产品索引视图中使用“type_name”来显示每个产品的产品类型

代码 姓名 类型_名称
P0001 牛角面包 维也纳音乐
p0002 萨赫蛋糕 蛋糕
P0003 奶油蛋卷开心果 维也纳音乐
P0004 泡芙巧克力 泡芙
...... ........................ .........

但我不能使用 type_name 来按这样的 type_name 排序产品集合

代码 姓名 类型_名称
p0002 萨赫蛋糕 蛋糕
P0004 泡芙巧克力 泡芙
P0001 牛角面包 维也纳音乐
P0003 奶油蛋卷开心果 维也纳音乐
...... ........................ .........

我尝试搜索 S.O.和谷歌一般,但似乎很少有这个相当常见的问题,我尝试了建议的解决方案(使用scope或Arel)但没有成功

ruby-on-rails activerecord
1个回答
0
投票

解决方案是

Product.joins(:product_type).order('product_types.name ASC')

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.