업 후, 그는 어떻게든지 2..3
대신 Product
경우 레코드루비 블록이 <a href="http://railscasts.com/episodes/396-importing-csv-and-excel" rel="nofollow">screencast</a>을
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
포스터의 원래 방법에서 #each 대신 #collect (http://www.ruby-doc.org/core-2.1.1/Array.html#method-iCollect)를 사용하십시오. – RipTheJacker
@mattwise에 감사드립니다. Ryan이'ruby 1.9.2'와 함께'rails 3.2.9'와 동일한 코드를 사용하고 있기 때문에 ruby 나 rails 버전 문제로 생각했습니다. –