简体   繁体   中英

Rails 4 Script + Error: Migrating Data From One Table to Another

I have created a script that I want to use to populate a new table in another database, as I'm moving this table out of one DB(table_1) and into another DB(db_2). I've already created the 'new_geo_fence' table in the new DB (db_2) and want to have the script run below to migrate data over. Script below:

class NewGeoFence < ActiveRecord::Base
attr_accessible :name, :address, :latitude, :longitude, :radius, :customer_id

      belongs_to :customer, :foreign_key => 'customer_id'
    end

require 'rubygems'

GeoFence.all.each do |g|
  gf = NewGeoFence.new(
    :id => g.id,
    :name => g.name,
    :address => g.address,
    :latitude => g.latitude,
    :longitude => g.longitude,
    :radius => g.radius,        
    :created_at => g.created_at,
    :updated_at => g.updated_at, 
    :customer_id => g.customer_id
  )
  gf.save
end

However, when I run it, I get this error:

/activerecord-4.0.13/lib/active_record/attribute_assignment.rb:47:in `rescue in _assign_attribute': unknown attribute: customer_id (ActiveRecord::UnknownAttributeError)

What have I missed to get this script running?

Thanks!

您应该在对象数组上调用类时调用它们,因此

GeoFence.all.each do |g|

Rails 4 requires parameters to be whitelisted when doing mass assignment. To do so, use strong parameters

GeoFence.all.each do |g|
  params = ActionController::Parameters.new({
    geofence: {
      id: g.id,
      name: g.name,
      address: g.address,
      latitude: g.latitude,
      longitude: g.longitude,
      radius: g.radius,        
      created_at: g.created_at,
      updated_at: g.updated_at, 
      customer_id: g.customer_id
     }
  })
  gf = NewGeoFence.new(params.require(:geofence).permit!)
  gf.save
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM