在一个创建表单上保存多个记录取决于关联的项目

时间:2019-06-12 18:34:10

标签: ruby-on-rails ruby ruby-on-rails-4

目标:根据存在的某些关联记录创建多个订单。

形式如下:(不重要,但会收到错误

<%= form_for(@order) do |form| %>
    <%= form.hidden_field :cart_id, value: @cart.id %>
    <%= form.hidden_field :store_order_id, value: "1" %>
    <%= form.text_field :shipping_name %>
    <%= form.text_field :shipping_address1 %>
  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

错误:

  

ActionView :: Template :: Error(表单中的第一个参数不能包含nil   或为空):

型号:

ShopProduct

has_one :order
has_many :line_items

订购

belongs_to :product, optional: true
belongs_to :shop_product, optional: true
belongs_to :cart

LineItem

belongs_to :shop_product, optional: true
belongs_to :product, optional: true
belongs_to :cart

购物车

has_many :line_items, dependent: :destroy
has_one :order

OrdersController:

  def create
    cart = Cart.find(params["order"]["cart_id"])
    line_items = LineItem.where(cart_id: cart)
    shop_product_line_items = line_items.where.not(shop_product: [nil, ""])
    product_line_items = line_items.where.not(product: [nil, ""])
    shop_products = ShopProduct.find(shop_product_line_items.each { |li| li.shop_product })
    products = Product.find(product_line_items.each { |li| li.product })

    if shop_products.present?
      shop_products.each { |sp|
      @order = Order.new
      @order.shop_product_id = sp.id
      @order.product_id = sp.product_id
      @order.cart_id = cart
      @order.save!
    }
    end

    if products.present?
      products.each { |p|
      @order = Order.new
      @order.product_id = p.id
      @order.cart_id = cart
      @order.save!
    }
    end

    @orders = Order.where(cart_id: cart)

    respond_to do |format|
      if @orders.count == line_items.count
        session[:cart_id] = nil
        format.html { redirect_to @order, notice: 'Order was successfully created.' }
        format.json { render :show, status: :created, location: @order }
      else
        format.html { render :new }
        format.json { render json: @order.errors, status: :unprocessable_entity }
      end
    end
  end

工作原理是有一个购物车,然后将其连接到许多line_itemsshop_product的{​​{1}}上。然后,我想根据每个product保存一个单独的订单。

如何根据购物车中有多少line_items创建多个订单?

0 个答案:

没有答案
相关问题