Note that there are some explanatory texts on larger screens.

plurals
  1. PORails validation for a has_many association
    text
    copied!<p>I am having trouble with validations on a has_many relationship where the children exist, but the parent doesn't. However, when creating/saving the parent object, I want to ensure that specific children (with certain attributes) have already been saved.</p> <p>There is a <code>Parent</code> object that <code>has_many</code> <code>Child</code> objects. The <code>Child</code> objects are persisted into the database first, and thus don't have any reference to the parent. The association structure is:</p> <pre><code>Parent - has_many :children Child - someProperty: string - belongs_to: parent </code></pre> <p>For example, there are three child objects:</p> <pre><code>#1 {someProperty: "bookmark", parent: nil} #2 {someProperty: "history", parent: nil } #2 {someProperty: "window", parent: nil } </code></pre> <p>A parent is valid only if it contains child objects with someProperty <code>history</code> and <code>window</code>.</p> <p>I am setting up the parent inside the controller as:</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 // save the parent object p now p.save! </code></pre> <p>When the children are assigned to the parent with <code>&lt;&lt;</code>, they are not saved immediately as the parent's id does not exist. And for the parent to be saved, it must have at least those 2 children. How could I solve this problem? Any input is welcome.</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