简体   繁体   中英

How to run validations in Rails rake task

I have a rake task that imports data from a CSV file, its working very well. Now problem is I want to add more data to already existing data in my mysql table. Now this CSV file contains some data that is already imported into mysql. How can I skip data that is in CSV and in mysql already? I want to avoid duplicated in mysql table. Here is my working rake task.

namespace :populate_honda do
 desc "TODO"
  task pop_honda: :environment do
   vehicleid = Vehicle.where("name = 'Honda'").first.id
   Model.where(:vehicle_id => vehicleid).destroy_all
   honda_file = File.read(Rails.root.join('lib', 'tasks', 'honda.csv'))
   honda_list = CSV.parse(honda_file, :headers => true)
   honda_list.each do |m|
    t = Model.new
    t.name = m['model_name'].titleize
    t.vehicle_id = vehicleid
    t.createdate = Date.today
    t.user_id = 99
    t.save
   end
   puts honda_list.length.to_s + " Honda models successfully imported"
 end
end

I tried adding validates_uniqueness_of :name just below namespace :populate_honda do but its giving me a no method error. How can I achieve my intended goal?

您应该将validates_uniqueness_of :name放在Model类文件中,因为验证属于ActiveRecord类。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM