Operation to create a collection

229 views Asked by At

I want to create an operation which accepts a json array and creates several objects. Something like Books::CreateCollection. I believe I need to somehow reuse Books::Create - just call it multiple times and wrap the whole loop in transaction.

json:

{
 "books": [
    {
       title: "A Tale Of Two Cities"
    },
    {
       title: "Don Quixote"
    }
 ]
}

But how the contract of Books::CreateCollection should look like?

Trailblazer 0.3.0

1

There are 1 answers

1
apotonick On

Your contract can handle this.

contract do
  model Book # since you don't call this on the operation.

  collection :songs, populate_if_empty: Book do
    property :title
  end
end

This is basic Reform wizardry.

The contract will now create one Book instance per incoming hash fragment in the songs array.