2

嗨,我正在使用friendly_id gem,

class Student < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, use: :slugged

这里 Student.create 根据需要生成一个 slug 作为名称。

但就我而言,我正在使用“新”方法创建学生数组并使用活动记录导入保存到数据库

student_names.uniq.each do |s|
  students << Student.new(name: s)
end

Student.import students, on_duplicate_key_update: {
    conflict_target: [:name],
    timestamps: true
}

在“新”上,它不会创建 slug,也不会在导入时创建。

如何在导入时生成 slug?提前致谢

4

1 回答 1

4

FriendlyId 使用before_validation回调来生成和设置 slug ( doc ),但activerecord-import不调用 ActiveRecord 回调 ...( wiki )。

因此,您需要before_validation手动调用回调:

students.each do |student|
  # Note: if you do not pass the `{ false }` block, `after_callback` will be called and slug will be cleared.
  student.run_callbacks(:validation) { false }
end
Student.import ...
于 2016-11-21T11:17:39.393 回答