【问题标题】:Disabling callbacks in data migration with ActiveRecord - Ruby/Rails 5使用 ActiveRecord 禁用数据迁移中的回调 - Ruby/Rails 5
【发布时间】:2021-09-16 12:25:48
【问题描述】:

我正在通过如下所示的函数将 CSV 文件导入我的数据库中:

def import_csv_into_db
        CSV.foreach(Rails.root.join('db', 'csv_export',filename), headers: true) do |row|
          class_name = filename_renamed.constantize
          next if row.to_hash['deleted_at'] != nil
          Customer.before_create.reject! {|callback| callback.method.to_s == 'unique' }
          Customer.create!(row.to_hash)
        end
      end

我正在测试的当前文件是customers.csv。

我想跳过方法,或者更好地说,回调是 当我创建对象以将数据插入相应的数据库时触发,例如Customer.create!(row.to_hash)

这就是我尝试实现以下方法的原因:

Customer.before_create.reject! {|callback| callback.method.to_s == 'unique' }

这样我就可以跳过来自 customer.rb 模型的回调

但我得到了错误:

ArgumentError: wrong number of arguments calling `method` (0 for 1)

我理解错误,但我不明白的是如何正确实现上面提到的Customer.before_create 行。

我的方法在seeds.rb 中实现,并在运行rake db:seed 时触发,是的,它可以与其他CSV 一起正常工作,只是带有回调 的方法会造成问题.

我找到了.before_create.reject 方法here

【问题讨论】:

  • 您要使所有回调静音还是只静音一个特定的回调?
  • @the_spectator 通常是所有这些,或者你能不能展示一下如何做到这两点?

标签: ruby-on-rails ruby csv activerecord callback


【解决方案1】:

错误来自callback(在您的块中)是一个对象,并且它的method 方法返回一个给定名称的方法。即:'a string'.method(:upcase)SomeClass.method(:new)

您可以使用insert! 代替create!,这会跳过所有内容,但是您必须添加所有需要的列(包括时间戳):

attributes = row.to_hash
attributes['created_at'] = attributes['updated_at'] = DateTime.now.utc
class_name.insert!(attributes)

【讨论】:

    猜你喜欢
    • 2017-12-14
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    相关资源
    最近更新 更多