Ruby 如何在rake任务中更新多态图像?
我有一个厕所和照片模型,照片有一个多态关联。 我有一个rake任务,它从csv文件收集信息。我想更新图片,但因为它不是厕所表的一部分,所以我很难弄清楚。我用回形针来处理我的图像 我的任务是这样的Ruby 如何在rake任务中更新多态图像?,ruby,ruby-on-rails-5,Ruby,Ruby On Rails 5,我有一个厕所和照片模型,照片有一个多态关联。 我有一个rake任务,它从csv文件收集信息。我想更新图片,但因为它不是厕所表的一部分,所以我很难弄清楚。我用回形针来处理我的图像 我的任务是这样的 namespace :import do desc "Importing toilets from csv" task toilets: :environment do filename = File.join Rails.root, "toilets.csv" counter =
namespace :import do
desc "Importing toilets from csv"
task toilets: :environment do
filename = File.join Rails.root, "toilets.csv"
counter = 0
CSV.foreach(filename, headers: true) do |row|
toilet = Toilet.create(
name: row['name'],
latitude: row['latitude'],
longitude: row['longitude'],
address: row['address'],
image: row['image']
)
puts "#{toilet} - #{toilet.errors.full_messages.join(",")}" if toilet.errors.any?
counter += 1 if toilet.persisted?
end
puts "Imported #{counter} toilets"
end
end
厕所模型
has_many :photos, :as => :imageable
accepts_nested_attributes_for :photos
照片模型
belongs_to :toilet
belongs_to :imageable, :polymorphic => true
has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
我想出了如何用下面的代码更新图像。这是可行的,但我觉得可能有一个更干净的解决方案
toilet = Toilet.create(
name: row['name'],
latitude: row['latitude'],
longitude: row['longitude'],
address: row['address']
)
photo = Photo.create(
image: row["image"],
imageable_type: "Toilet",
imageable_id: toilet.id
)