[英]update multiple tables in rails in one json post
hi can you help me to update multiples table tables in rails actually this post request 您好,您能帮我更新Rails中的多张表吗?
{
"order":
{
"subsidiary_id":1,
"user_id":1,
"amount":220,
"order_itens_attributes":
[
{
"quantity":22,
"product_id": 1
},
{
"quantity":22,
"product_id": 1
}
]
}
}
and this response in json 这个响应在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"
}
]
}
and i have this in my controller 我的控制器中有这个
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
and my models that I have is 我的模特是
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
actually i want to do two things, validate if we have products in my inventory and reduce de inventory quantity once went i send the json post 实际上,我想做两件事,验证库存中是否有产品,一旦去就减少库存数量,然后发送json帖子
I think callbacks will do the trick in your case. 我认为回调可以解决您的问题。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.