【问题标题】:Acts As Tree: assigning parent to a child with letting parent know about it?充当树:将父母分配给孩子并让父母知道?
【发布时间】:2019-12-27 15:16:11
【问题描述】:
当我像这样手动将父母分配给孩子时:
parent = create :rule # I'm using FactoryBot to create test data
child = create :rule, parent: parent
那么家长就不知道了:
parent.children # => []
如何确保家长了解新孩子?目前,我手动将孩子分配给父母:
parent.children << child
但这感觉很古怪。有没有更好的方法?
【问题讨论】:
标签:
ruby-on-rails
acts-as-tree
【解决方案1】:
在您的工厂:
## spec/factories/rules.rb
factory :rule do
attribute_1 { 'bla' }
...
trait :with_child do
association :child, factory :rule
end
这会让你从你的规范中调用:
child = create(:rule, :with_child).children.first
并且将在一行中创建您的父母和孩子,或者如果您需要将两者都分配给一个变量:
parent = create(:rule, :with_child)
child = parent.children.first