【发布时间】:2019-11-14 05:26:43
【问题描述】:
我有一些模型基本上看起来像:
class Parent < ApplicationRecord
has_many :children
end
class Child < ApplicationRecord
belongs_to :parent
belongs_to :child_type
end
class ChildType < ApplicationRecord
has_many :children
end
有 3 个 ChildType 条目,当我创建一个新的 Parent 对象时,我想继续创建依赖的 Child 对象,每个子类型一个。
有没有更简洁的方法来做这件事,而不是:
class Parent < ApplicationRecord
has_many :children
after_create :create_children
private
def create_children
ChildType.all.each do |ct|
children.create(child_type_id: ct.id)
end
end
end
这行得通,但我想知道 rails 是否有更清洁的方式来做到这一点。
其次,我还想要父级的快捷方法,以便我可以轻松地按类型访问三个子级:
Parent.find(id).child_type_1 # returns children.where(child_type: { id: 1 }).first
我可以在 Child 上创建一个接受类型参数的作用域,但如果可能的话,我宁愿在父级上有一个方法来加载它,如果有一种干净的方法可以做到这一点。我可以在父级上创建 3 种方法来找到每种类型的合适子级,但这不是超级 DRY...
【问题讨论】:
标签: ruby-on-rails activerecord ruby-on-rails-6