我有一些基本上看起来像的模型:
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
ChildType有3个条目,当我创建一个新的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 ...