Home>

Is there a way to remove some child elements from the already generated model in the Rails has_many relationship?
As a premise, model instances of parent 1: n are generated based on params.

Corresponding source code

(I just wrote it as an example. There may be a description error.)
Model side

class Order</pre>
<p><br />
Controller side</p>
<pre><code>@order = Order.new (order_params)
I want to remove unnecessary items from items before #save (for example, when items with quantity 0 are not needed on the DB)
@ order.save
def order_params
 params.require (: order) .permit (: no, items_attributes: [: quantity,: price])
end
What I tried

In fact, there is only one implementation that is actually working.

@ order.items.target.delete_if {| item | item.quantity.zero?}


However, I personally find it very difficult to understand.
(What you retrieve with target looks like another new object, and even if you edit it, it will change.)
I would like to have a more understandable implementation method.

  • Answer # 1

    How about playing at the verification timing of strong parameters?
    I don't think this will create unnecessary item instances either.

    Example: When the item with quantity 0 is unnecessary

    def order_params
      params.require (: order) .permit (: no,
                                    items_attributes: [: quantity,: price]). tap do | p |
                                      p [: items_attributes] .reject! {| i | i [: quantity] .to_i.zero?}
                                    end
    end

  • Answer # 2

    In this case, [Remove child element] means that you may delete the child element, right?

    Then
    items = Expression to get the Items to be removed items.delete_all
    Is fine.
    If the Expression to get the Item to be removed returns an Array instead of a Relation
    items.each {| item | item.delete}

Related articles