Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First thing, if you want the children to be saved without the parent id then there is no point in doing this</p> <pre><code> p = Parent.new(params[:data]) for type in %w[bookmark_id history_id window_id] if !params[type].blank? p.children &lt;&lt; Child.find(params[type]) end end </code></pre> <p>the whole purpose of </p> <pre><code> p.children &lt;&lt; some_child </code></pre> <p>is to attach the parent id to the child object which you are not doing here because the parent doesn't exist yet.</p> <p>The other thing is if you just want to make sure that the parent has a child object and if you are creating child and parent together then you can use transaction block around the parent and child creation which will make sure that the parent has child, like</p> <pre><code> transaction do p = create_parent p.children &lt;&lt; child1 p.children &lt;&lt; child2 end </code></pre> <p>So, within the transaction, if at any stage code fails then it will rollback the whole db transaction , i.e you will either have one parent with 2 children or nothing, if that's the end state you are looking for.</p> <p>EDIT: Since you can't create a parent unless it has 2 children, in that case, instead of</p> <pre><code>p = Parent.new(params[:data]) for type in %w[bookmark_id history_id window_id] if !params[type].blank? p.children &lt;&lt; Child.find(params[type]) end end </code></pre> <p>do</p> <pre><code> children = [] for type in %w[bookmark_id history_id window_id] if !params[type].blank? children &lt;&lt; Child.find(params[type]) end end if children.size &gt;= 2 p = Parent.create!(params[:data]) children.each {|child| p.children &lt;&lt; child} end </code></pre> <p>Does that make sense</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload