Rails嵌套关联不保存

时间:2017-06-02 18:25:15

标签: ruby-on-rails ruby-on-rails-5

我正在尝试保存嵌套关联,但由于某种原因它无法正常工作。有没有人看到这个有什么问题?

Order:
class Order < ApplicationRecord
  has_many :replenishable_products, through: :order_items
  has_many :order_items
  accepts_nested_attributes_for :order_items
end


OrderItem
class OrderItem < ApplicationRecord
  belongs_to :order
  has_one :replenishable_product
  accepts_nested_attributes_for :replenishable_product
end

ReplenishableProduct
class ReplenishableProduct < ActiveRecord::Base
  belongs_to :order_item
end

Order Controller
def create
  @order = @customer.orders.new(order_params)
  authorize @order

  if @order.save
    render json: @order, serializer: ::V1::OrderSerializer, status: :created
  else
    render json: @order.errors, status: :unprocessable_entity
  end
end

def order_params
  params.require(:order).permit(order_items_attributes: [:quantity, :product_id, :selling_unit_of_measure_id,
                                replenishable_product_attributes: [:product_id, :salesperson_id,
                                :customer_id, :replenishable_date]])
end


Example request data:
```
{"order"=><ActionController::Parameters {"additional_tax_total"=>"8.27", "basket_id"=>"1", "custom_order_number"=>"pf000", "customer_attributes"=>{"contact_name"=>"Jason Test", "email"=>"new@test.com", "phone"=>"6095453234"}, "order_items_attributes"=>[{"product_id"=>"1", "quantity"=>"5", "replenishable_product_attributes"=>{"customer_id"=>"1", "product_id"=>"1", "replenishable_date"=>"2017-06-09T13:00:39-04:00", "salesperson_id"=>"1"}, "selling_unit_of_measure_id"=>"1"}, {"product_id"=>"2", "quantity"=>"5", "selling_unit_of_measure_id"=>"2"}], "payment_total"=>"103.31", "salesperson_id"=>"1", "shipping_address"=>"Test", "special_instructions"=>"test"} permitted: false>, "customer_id"=>"1", "format"=>"json", "controller"=>"api/v1/orders", "action"=>"create"}
```

所以其他所有关联都保存得很好,但replenishable_product没有被保存。我看了几遍,我不明白为什么不能保存。有人有什么想法吗?

0 个答案:

没有答案