我正在尝试使用每日 RAKE 任务将我的应用程序中的用户表与 CSV 文件同步。
我的 import.rake 任务成功导入了在表中找不到的记录 (find_or_create_by_username),但我不知道如何从表中删除 CSV 文件中不再找到的记录。我应该用什么代替“find_or_create_by_username”来实现这一点?提前致谢。
#lib/tasks/import.rake
desc "Import employees from csv file"
task :import => [:environment] do
file = "db/testusers.csv"
usernames = [] # make an array to collect names
CSV.foreach(file, headers: true) do |row|
Employee.find_or_create_by_username({
# Add this line:
username = row[0]
:username => username,
:last_name => row[1],
:first_name => row[2],
:employee_number => row[3],
:phone => row[4],
:mail_station => row[5]
}
)
# Collect the usernames
usernames << username
end
# Delete the employees (make sure you fire them first)
Employee.where.not( username: usernames ).destroy_all
end