ruby-on-rails - 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)
解决方案
推荐阅读
- c# - 需要修改导航方法以使导航多于一个
- multithreading - 彼得森的进程调度解决方案
- ruby-on-rails - 如何根据评分将所有成员分成独立的公平团队?
- python - 定义一个列表并使用循环打印该列表
- python - 测试函数的 AssertionError
- swift - Swift:假设具有初始值的“let”字段是静态的
- python - 旨在开发区分不同面孔的张量流模型
- reactjs - 如何覆盖组件中使用的 antd 的默认 svg 图标?
- python - 自动打印多页word文档到pdf
- python-3.x - 我收到 File not found 错误,似乎不是编码问题