Rails 4脚本+错误:将数据从一个表迁移到另一个表

时间:2015-04-07 00:39:57

标签: mysql ruby-on-rails ruby ruby-on-rails-4

我创建了一个脚本,我想用它来填充另一个数据库中的新表,因为我将这个表从一个DB(table_1)移到另一个DB(db_2)。我已经在新数据库(db_2)中创建了'new_geo_fence'表,并希望在下面运行脚本来迁移数据。下面的脚本:

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

然而,当我运行它时,我收到此错误:

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

我错过了让这个脚本运行的内容?

谢谢!

2 个答案:

答案 0 :(得分:0)

当你应该在一个对象数组上调用它时,你正在调用每个类,所以

GeoFence.all.each do |g|

答案 1 :(得分:0)

Rails 4要求在进行批量分配时将参数列入白名单。为此,请使用强参数

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