Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
Bulk creating objects with nested attributes in ruby

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
        }
      ]
    },
  ]
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!