首页 > 解决方案 > Rails 按多态属性排序

问题描述

我有以下型号:

class Item < ApplicationRecord
    has_ancestry cache_depth: true, orphan_strategy: :destroy

    belongs_to :user
    has_many :shortcuts
    belongs_to :itemable, :polymorphic => true, dependent: :destroy
    accepts_nested_attributes_for :itemable

    attr_accessor :key

    def key
        self.itemable.key
    end
end

class Folder < ApplicationRecord
    has_one :item, as: :itemable, dependent: :destroy
    accepts_nested_attributes_for :item
end

class Field < ApplicationRecord
    has_one :item, as: :itemable, dependent: :destroy
    accepts_nested_attributes_for :item
end

我希望能够通过 itemable 上的 :key 属性对结果进行排序(文件夹和字段都有名为 :key 的属性),IE

Item.all.include(:itemable).order("itemable.key ASC")

我想出了一种通过 attr_accessor 做智慧的方法,但不确定这是否是正确的方法:

Item.all.sort_by(&:key)

标签: ruby-on-railspolymorphic-associations

解决方案


推荐阅读