我正在将带有产品信息的csv文件导入rails 4应用程序。我在csv中有四个图像字段。如果某些产品的图像少于4个,则不会加载该文件。
以下是模型中的导入代码:
def self.import(file, userid)
CSV.foreach(file.path, headers: true) do |row|
listing_hash = {:name => row['Name'], :description => row['Description'],
:price => row['Price'], :category => row['Category'], :inventory => row['Inventory'],
:image => URI.parse(row['Image']), :image2 => URI.parse(row['Image2']),
:image3 => URI.parse(row['Image3']), :image4 => URI.parse(row['Image4']),
:userid => userid}
listing = Listing.where(name: listing_hash["name"])
if listing.count == 1
listing.first.update_attributes(listing_hash)
else
Listing.create!(listing_hash)
end # end if !product.nil?
end # end CSV.foreach
end # end self.import(file)
模型中的验证声明甚至不需要单个图像。
validates :name, :description, :price, :inventory, :category, presence: true
如何修复它以便即使产品没有全部4张图像也能导入csv?
答案 0 :(得分:1)
您可以执行以下操作:
CSV.foreach(file.path,headers:true)do | row |
listing_hash = {:name => row['Name'], :description => row['Description'],
:price => row['Price'], :category => row['Category'], :inventory => row['Inventory'],
:userid => userid}.tap do |list_hash|
list_hash[:image] = URI.parse(row['Image']) if row['Image']
list_hash[:image2] = URI.parse(row['Image2']) if row['Image2'] #repeat for each image
end
listing = Listing.where(name: listing_hash["name"])
if listing.count == 1
listing.first.update_attributes(listing_hash)
else
Listing.create!(listing_hash)
end # end if !product.nil?
end