3

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
        }
      ]
    },
  ]
}

1 Answer 1

7
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

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, thanks so much this worked perfectly and executes in only two SQL statements, thank you again!
Update: I found with just adding recursive: true to the import I did not need to do the build step done in the map
What happen if author is a belongs_to association and you want it to create author on books if it doesn't exist? e.g. books = 10.times.map do |i| book = Book.new(name: "Book Name #{i}") book.author = Author.new(name: "John Doe") book end Book.import books, recursive: true This code above doesn't create the Author if it doesn't exist even if you set accept_nested_attributes :author on Book model. Do you have any idea how to go about this?
recursive flag only works in PostgreSQL. It doesn't works with MySQL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.