Rails按多态属性排序

时间:2018-07-24 14:38:04

标签: ruby-on-rails polymorphic-associations

我有以下型号:

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的属性),即

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

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

Item.all.sort_by(&:key)

0 个答案:

没有答案