【发布时间】:2018-07-03 15:56:48
【问题描述】:
假设我有一个带有许多关联模型的 Car 模型,有些 has_many,有些 has_one。
class Car
include Mongoid::Document
has_one :steering, class_name: "Car::Steering", autosave: true, dependent: :destroy
accepts_nested_attributes_for :steering, allow_destroy: true
has_many :tires, class_name: "Car::Tire", autosave: true, dependent: :destroy
accepts_nested_attributes_for :tires, allow_destroy: true
has_many :doors, class_name: "Car::Door", autosave: true, dependent: :destroy
accepts_nested_attributes_for :doors, allow_destroy: true
end
如何列出每个Car 记录并显示每个关联模型记录的计数?
我想返回类似的东西:
parts = { steering: 1, doors: 4 }
我知道我可以逐个处理每个关联并返回计数,但是如果我有 100 个关联怎么办?我想让它动态化。
编辑:
我可以使用
获取所有关联的 has_many 和 has_one 记录的数组car = Car.first
Car.reflect_on_all_associations(:has_many, :has_one).map(&:name)
=> [:steering, :tires, :doors, ...]
【问题讨论】:
-
你知道你的模型中也可以有
embedded关联吗?你想把它们包括在你的计数中吗? -
@JagdeepSingh 我真的不介意这些记录是如何关联的,无论它们是嵌入的还是关联的。你有什么想法?
-
我有与您在下面发布的完全相同的解决方案。 :)
-
如果您需要所有类型的关联计数,您可能需要将其更改为
reflect_on_all_associations(:has_many, :has_one, :embeds_one, :embeds_many, :has_and_belongs_to_many, :belongs_to, etc.)
标签: ruby-on-rails mongoid