Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>merge</code> method that you're calling is just the usual Ruby <code>Hash#merge</code> method. For each key in the argument of <code>merge</code>, the value overwrites the value that is currently present for that key, if any. In this case, you are overwriting the value of <code>sections_attributes</code>.</p> <p>Since <code>sections_attributes</code> is a "pseudo-array" of the form <code>{"0" =&gt; first_hash, "1" =&gt; second_hash}</code> and so on, you need a way to duplicate your <code>user</code> once per entry. You can do that by using the ability of merge take a block that changes the merged value. Here's one approach:</p> <pre><code>filtered_params = params.require(:post) .permit([:title, :body, sections_attributes: [:title, :section_type]]) additional_params = {user: current_user, sections_attributes: [user: current_user]} result = filtered_params.merge(additional_params) do |key, oldval, newval| if newval.is_a? Array # Arrays are expected to be one-element arrays containing a Hash that is # supposed to be merged into each element of the currently-existing # "pseudo-array" oldval ||= {} Hash[oldval.map {|k, v| [k, v.merge(newval.first)]}] elsif newval.is_a? Hash # Hashes are merged into existing hashes oldval ||= {} oldval.merge newval else # Other types are passed as-is (and replace any existing value) newval end end # This marks the newly added parameters as permitted. It's only necessary because we # made new Hashes when we modified the "pseudo-array" result.permit! </code></pre> <p>If you find that this works for you, you could encapsulate this in a method, either by taking the inside of the block and making it a separate method, or by installing the whole thing as a named method on the <code>Parameters</code> class.</p> <p>Note also that the above only handles one layer of recursion. Going deeper than this is a bit tricky. If you need to do it, I'd be happy to write up an explanation.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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