Question
For a nested model, how do I create multiple copies of it, as specified in it's quantity attribute.
Usecase
This is especially done when making invoices. If your invoice is a model, and the line items are nested models with a quantity
field. How do you save n copies of the line-items in the databases, where n
is given in the quantity
field?
Details
I have two models:
class PurchaseOrder < ApplicationRecord
has_many :containers
accepts_nested_attributes_for :containers, reject_if: :all_blank, allow_destroy: true
end
class Container < ApplicationRecord
belongs_to :purchase_order
end
For my PurchaseOrdersController#create
action, the params it receives are in the form:
params = {
purchase_order: ...
containers_attributes: [
<container>:
size: ...
price: ...
quantity: ...
}
if i get a container_attribute in the form:
{
size: 'large'
price: 20
quantity: 3
}
I need to create 3
containers of the form:
{
size: 'large'
price: 20
}
Essentially, how do I mutate the params without running into:
DEPRECATION WARNING: Method to_a is deprecated and will be removed in Rails 5.1, as
ActionController::Parameters
no longer inherits from hash.
Or, if mutating params is a bad idea, how do I edit container attributes before they're saved!