We are encountering a problem in a new app we are creating. We have two models: Packages and products, a package has many products. We need to create a controller that can bulk create packages so we started using the activerecord-import gem which allows for bulk creates. However the problem is that the gem does not allow for the use of nested attributes to create products, which means I cannot create the corresponding products for each package. Has anyone encountered a similar problem or have any potential elegant solutions?
The JSON for the controller would be similar as below.
{
packages: [
{
weight: 'x',
products_attributes: [
{
code: x
},
{
code: x
}
]
},
{
weight: 'y',
products_attributes: [
{
code: y
},
{
code: y
}
]
},
]
}
CodePudding user response:
books = 10.times.map do |i|
book = Book.new(name: "book #{i}")
book.reviews.build(title: "Excellent")
book
end
Book.import books, recursive: true
You can try this, iterate your hash, and build objects for packages, and for each package, iterate products, and build products objects assigned to package object. Another way - is build raw SQL, but it's harder