【发布时间】:2023-03-03 00:36:01
【问题描述】:
跟进这个screencast,如果有Product记录,它会以某种方式返回2..3
def save
puts "--- imported_products: #{imported_products.inspect}"
// --- imported_products: 2..3
if imported_products.map(&:valid?).all?
imported_products.each(&:save!)
true
else
imported_products.each_with_index do |product, index|
product.errors.full_messages.each do |message|
errors.add :base, "Row #{index+2}: #{message}"
end
end
false
end
end
def imported_products
@imported_products ||= load_imported_products
end
def load_imported_products
spreadsheet = open_spreadsheet
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
product = Product.find_by_id(row['id']) || Product.new
product.attributes = row.to_hash.slice(*accessible_attributes)
product
end
end
【问题讨论】:
标签: ruby ruby-on-rails-4 ruby-2.1