Hi I am using friendly_id gem,
class Student < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: :slugged
Here Student.create generates a slug as name as required.
But in my case, I am creating array of Student using 'new' method and saving to database using 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
}
On 'new', it doesn't create slug and also on import.
How can I generate slug on import? Thanks in advance
FriendlyId uses a before_validation
callback to generate and set the slug
(doc), but activerecord-import
does NOT call ActiveRecord callbacks ...(wiki).
So, you need to call before_validation
callbacks manually:
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 ...