Rails友好ID:未在model.new或model.import上生成slug

时间:2016-10-27 17:03:13

标签: ruby-on-rails ruby slug friendly-id activerecord-import

您好我正在使用friendly_id gem,

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

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

但就我而言,我正在使用'new'方法创建Student数组并使用active-record-import保存到数据库

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

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

在'new'上,它不会创建slug,也会导致导入。

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

1 个答案:

答案 0 :(得分:3)

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 ...