Firstly, if you want children to be saved without a parent identifier, then there is no point in doing this
p = Parent.new(params[:data]) for type in %w[bookmark_id history_id window_id] if !params[type].blank? p.children << Child.find(params[type]) end end
whole goal
p.children << some_child
consists in attaching a parent identifier to a child object that you are not executing here because the parent does not exist yet.
Another thing is if you just want to make sure that the parent has a child, and if you create child and parent elements together, you can use the transaction block around the parent and child creation, which will ensure that the parent is a child, for example
transaction do p = create_parent p.children << child1 p.children << child2 end
Thus, within the framework of the transaction, if at some stage the code crashes, it will roll back the entire transaction db, i.e. you will have either one parent with 2 children, or nothing if this is the final condition you are looking for.
EDIT: since you cannot create a parent if it does not have 2 children, instead
p = Parent.new(params[:data]) for type in %w[bookmark_id history_id window_id] if !params[type].blank? p.children << Child.find(params[type]) end end
do
children = [] for type in %w[bookmark_id history_id window_id] if !params[type].blank? children << Child.find(params[type]) end end if children.size >= 2 p = Parent.create!(params[:data]) children.each {|child| p.children << child} end
It makes sense
source share