Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda