обновить несколько таблиц в рельсах в одном посте json - PullRequest
0 голосов
/ 27 мая 2018

привет, вы можете помочь мне обновить таблицы таблиц с множественными числами в рельсах, на самом деле этот пост-запрос

{
    "order":
    {
        "subsidiary_id":1,
        "user_id":1,

        "amount":220,
        "order_itens_attributes": 
        [
            {
                "quantity":22,
                "product_id": 1

            },
            {
                "quantity":22,
                "product_id": 1

            }
        ]
    }

}

и этот ответ в json

{
    "id": 2,
    "user_id": 1,
    "subsidiary_id": 1,
    "amount": 220,
    "start_time": null,
    "arrive_time": null,
    "delivered_time": null,
    "cancel_time": null,
    "created_at": "2018-05-27T03:06:41.035Z",
    "updated_at": "2018-05-27T03:06:41.035Z",
    "order_itens": [
        {
            "id": 3,
            "order_id": 2,
            "product_id": 1,
            "quantity": 22,
            "created_at": "2018-05-27T03:06:41.037Z",
            "updated_at": "2018-05-27T03:06:41.037Z"
        },
        {
            "id": 4,
            "order_id": 2,
            "product_id": 1,
            "quantity": 22,
            "created_at": "2018-05-27T03:06:41.039Z",
            "updated_at": "2018-05-27T03:06:41.039Z"
        }
    ]
}

, и у меня есть это в моем контроллере

class OrdersController < ApplicationController

  # POST /orders
  # POST /orders.json
  def create
    @order = Order.new(order_params)

    if @order.save
      render json: @order, include:[:order_itens], status: :created, location: @order
    else
      render json: @order.errors, status: :unprocessable_entity
    end
  end

  private

    def order_params
      params.require(:order).permit(
        :user_id, :subsidiary_id, :amount, :start_time,
         :arrive_time, :delivered_time, :cancel_time,
         order_itens_attributes: [:quantity,:product_id])
    end
end

и мои модели, которые у меня есть,

class OrderIten < ApplicationRecord
  belongs_to :order, optional: true
  belongs_to :product, optional: true
end

class Order < ApplicationRecord
  belongs_to :user
  belongs_to :subsidiary#, optional: true
  has_many :order_itens
  accepts_nested_attributes_for :order_itens

end

class Inventory < ApplicationRecord

      belongs_to :product
      belongs_to :subsidiary
        end

на самом деле я хочу сделать две вещи, подтвердите, если у нас есть продукты вмой инвентарь и уменьшение количества инвентаря, когда я пошел, я отправляю JSON сообщение

1 Ответ

0 голосов
/ 27 мая 2018

Я думаю, что обратные вызовы помогут вам в вашем случае.

class OrderIten < ApplicationRecord
  belongs_to :order, optional: true
  belongs_to :product, optional: true
  validate :available_quantity
  after_create :decrease_inventory

  private

  def available_quantity
    if quantity > product.inventory.quantity
      errors.add(:quantity, 'is higher than available in inventory')
    end
  end

  def decrease_inventory
    inventory = product.insventory
    inventory.update!(quantity: inventory.quantity - quantity)
  end

end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...