如何遍历 rails 中的嵌套数组

How to loop through nested array in rails

目前我正在探索 Ruby Rails。所以我尝试将嵌套数组保存在数据库中,但遇到了一些问题。问题是我可以从输入框中获取值,但不确定如何正确循环数据。

我参数中的值为

#<ActionController::Parameters {"authenticity_token"=>"HrR9-qX2HZrG3Q71smHdcO4s8ke8SwoUzhAZGdTOuVsuAq-RQO7Rp9YIX6j988uj9PTkA-pffvM2IBlKGi0C2w", "supplier"=>#<ActionController::Parameters {"company_id"=>"1", "first_name"=>"aa", "last_name"=>"aa", "username"=>"aa", "email"=>"aa@aa.com", "phone_number"=>"65738290"} permitted: false>, "supplier_item"=>{"item_ids"=>["2", "4"], "location_ids"=>["1", "2"], "supplier_prices"=>["7.8", "45.0"]}, "item_select"=>"1", "location_select"=>"1", "commit"=>"Create Supplier", "controller"=>"suppliers", "action"=>"create"} permitted: false>

我想做的是循环参数[:supplier_item]。这里面的数据是什么。

#<ActionController::Parameters {"item_ids"=>["2", "4"], "location_ids"=>["1", "2"], "supplier_prices"=>["7.8", "45.0"]} permitted: false>

所以我想循环参数 [:supplier_item] 并保存到名为 supplier_item 的连接 table 中。所以我尝试了几种方法来遍历数据,但我仍然遇到一些问题。

你们有任何意见或想法如何做到这一点,请分享。我在下面附上我的代码。谢谢

 @supplier = Supplier.new(supplier_params)
      if @supplier.save
        params[:supplier_item][:item_ids].each do |item_id|
          supplier_prices = params[:supplier_item][:supplier_prices]
          location_ids = params[:supplier_item][:location_ids]
          supplier_item = SupplierItem.new(item_id: item_id[], supplier_id: @supplier.id, location_id: location_ids[], supplier_price: supplier_prices )
          supplier_item.save
        end
        flash[:success] = "New supplier created"
        redirect_to supplier_path(@supplier)
      else
        render 'new'
      end

我假设 SupplierItem 对象属性应该取自 item_idslocation_idssupplier_prices 数组的相同索引。

代码:

@supplier = Supplier.new(supplier_params)
if @supplier.save
  item_params = params.require(:supplier_item).permit(item_ids: [], location_ids: [], supplier_prices: [])
  # => {"item_ids"=>["2", "4"], "location_ids"=>["1", "2"], "supplier_prices"=>["7.8", "45.0"]}
  items = item_params[:item_ids].zip(*item_params.values_at(:location_ids, :supplier_prices))
  # => [["2", "1", "7.8"], ["4", "2", "45.0"]]
  items.map do |item_id, location_id, supplier_price|
    supplier_item = SupplierItem.new({
      item_id:        item_id,
      location_id:    location_id,
      supplier_price: supplier_price,
      supplier_id:    @supplier.id,
    }.compact)
    supplier_item.save # TODO: check if it saved
  end
  flash[:success] = "New supplier created"
  redirect_to supplier_path(@supplier)
else
  render 'new'
end

PS: Don't use float/double for money.