【问题标题】:Rails Friendly ID: slug is not generated on model.new or model.importRails 友好 ID:在 model.new 或 model.import 上未生成 slug
【发布时间】:2017-03-10 11:31:49
【问题描述】:

您好,我正在使用friendly_id gem,

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

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

但就我而言,我正在使用“新”方法创建学生数组并使用 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
}

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

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-07-19
      • 2015-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-17
      • 2016-04-16
      • 2011-07-15
      • 2014-02-18
      相关资源
      最近更新 更多