跟进此screencast,如果2..3
记录
Product
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
答案 0 :(得分:2)
您的load_imported_products
方法包含each
块。该块是方法的最后一行,因此块的返回值成为方法的返回值。
尝试以下方法:
def load_imported_products
spreadsheet = open_spreadsheet
header = spreadsheet.row(1)
products = []
(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)
products << product
end
products
end
答案 1 :(得分:1)
或使用地图
def load_imported_products
spreadsheet = open_spreadsheet
header = spreadsheet.row(1)
products = (2..spreadsheet.last_row).map do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
product = Product.find(row['id'].to_i) || Product.new
product.attributes = row.to_hash.slice(*accessible_attributes)
product
end
end
find
方法使用id
时也不需要find_by_id,但我强制它为nil
整数或存储为string
。
答案 2 :(得分:0)
如果您正在讨论load_imported_products方法,那么尝试将每个产品添加到数组中,然后返回该数组。
我不确定该方法究竟返回了什么,但您可能需要显式返回一组产品。
所以
def load_imported_products
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)
products << product
end
return products
end