3
votes

I'm using Rails 2.3.5 and AR-extensions 0.9.3

I'm trying to bulk insert from one table to another table located on a different server / database. I don't want anything overwritten though. Just a simple insert at the end of the new table is good enough.

I noticed that I get this warning message: WARNING: Can't mass-assign these protected attributes: id

My former entries are being overwritten.. so how do I work around this?

Thanks!

Edit: Figured it out. Looks like all I have to is define an array of attributes I want (Excluding id) and feed that into the import function.

Update:

tableA_items = TableA.find(:all)

TableB.establish_connection("other_server")
TableB.import tableA_items
3
Can you post the code you're using to do this? - Dylan Markow
attr_accessible :foo means you authorize foo's mass-assignment - apneadiving
update with code. does that mean rails will automatically modify the ids in this example? - Tommy

3 Answers

1
votes

This bug existed in ar-extensions (up to 0.9.5 in which it was fixed) and activerecord-import (up to 0.2.7 in which it was fixed).

ar-extensions is used for Rails 2.x. activerecord-import should be used for Rails 3.x. They support the same APIs.

0
votes

You could set the id column to nil on the imported items before running the import to avoid the mass_assignment problem:

tableA_items.each {|item| item.id=nil}

Note: It looks like there's a new version of this gem you might want to look at: https://github.com/zdennis/activerecord-import

0
votes

I still see this same error when using activerecord-import 0.2.7 + Rails 3.0.7, but when importing data from an external XML file. Here's the whole thing (as a Rails migration; I wasn't sure how else to run it):

require 'open-uri'

artists = Array.new
Artist.establish_connection("http://localhost:3000")

begin
  open("*some-url*") do | artists_file |
    artists_file.each do | line |
      if line =~ /<artist id="([\w_]*)" name="(.*)"[ <]/
        puts $1, $2

        if line =~ / sort="(.*)"/
          puts $1
        end

        begin
          artist = Artist.new(:id => $1, :name => $2)
          artists << artist
        rescue
          puts "Couldn't add " + $1 + ": " + $!
        end
      end
    end

    Artist.import artists, :validate => true
  end
rescue
  puts "Couldn't open the artists file."
end

EDIT: nevermind; the problem is that I AM explicitly trying to set the ID value. D'oh!