gpt4 book ai didi

ruby-on-rails - Rails 友好 ID : slug is not generated on model. 新的或 model.import

转载 作者:数据小太阳 更新时间:2023-10-29 08:35:59 24 4
gpt4 key购买 nike

您好,我正在使用 friendly_id gem,

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

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

但就我而言,我正在使用"new"方法创建学生数组并使用 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?提前致谢

最佳答案

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

关于ruby-on-rails - Rails 友好 ID : slug is not generated on model. 新的或 model.import,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40290412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com