Здесь можно устранить большую логику, запомнив два факта: create
примет массив хэшей для создания нескольких объектов, а его аналог метода взрыва create!
сгенерирует исключение в случае неудачной проверки.
def create_multiple
# like clyfe said, do this in a transaction
Product.transaction do
begin
@products = current_user.products.create!(
# Hash#map returns an Array, so no need to use Hash#values
params[:products].map { |_k, up| up.merge params[:product] }
)
# if create! is successful...
redirect_to :back, :notice => "Success!"
# if it's not successful it'll throw this exception, which we can rescue
rescue ActiveRecord::Rollback
redirect_to :back, :notice => "An error occured, please try again."
end
end
end
Один из способов решить проблему create!
- просто избавиться от любых «пустых» записей в before_filter
, например ::10000
before_filter :toss_blank_products
def toss_blank_products
params[:products].reject! do |prod|
# this logic may need to be more complex depending on the meaning of "blank"
# for your model/form
prod.values.all? &:blank
end
end