activerecord-import: has_many associations don't save with recursive: :true

Hello,

First, thank you very much for this gem, it is much appreciated every day from casual to complex data imports.

I am having troubles with the multi-level feature, when trying to import models with associations. I tried to follow the multi-level example this way:

I created a blank app with two models:

$ bundle exec rails g model Book title:string
$ bundle exec rails g model Review name:string book:references

Then I added the association to the Book model:

class Book < ActiveRecord::Base
  has_many :reviews
end

I created a basic rake task with the same code as the example, to insert books with one review in each, and checking at the end if everything went good:

task test: :environment do
  Book.delete_all
  Review.delete_all

  books = []
  10.times do |i|
    book = Book.new(title: "Book ##{i}")
    book.reviews.build(name: "Review ##{i}")
    books << book
  end
  Book.import books, recursive: true

  puts "'Book' records count: #{Book.count}"
  puts "Last 'Book' reviews count: #{Book.last.reviews.count}"
  puts "'Review' records count: #{Review.count}"
end

What I have in return shows that the books were inserted but not the associated reviews:

'Book' records count: 10
Last 'Book' reviews count: 0
'Review' records count: 0

I don’t know if my way of inserting associated models in database is wrong or if the multi-level feature has an issue, I thought it was the best place to warn about this behaviour has @sferik 's PR #230 (thank you for that btw) was supposed to fix it.

This test was run on Ubuntu 15.10 with:

  • rails v4.2.5.1
  • activerecord v4.2.5.1
  • sqlite3 v1.3.11
  • activerecord-import from Github (at master@df866a4)

This post is a duplicate from my comment on #243.

Thank you.

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 1
  • Comments: 21 (1 by maintainers)

Most upvoted comments

@yuri-karpovich sorry I should have added a comment to this before closing. Unfortunately there currently does not seem to be a good way to implement this feature for MySQL. See PR #279 for some more details. Unless MySQL implements an option to return inserted/updated IDs like PostgreSQL, we will not be able to make this work in a reliable way.