如何在使用rails_admin gem时,创建stock_in后自动更新product的数量?
在Rails Admin中创建StockIn后自动更新Product的quantity字段
1. 确认模型关联
先确保Product和StockIn的关联关系正确:
Product模型
class Product < ApplicationRecord has_many :stock_ins, dependent: :destroy end
StockIn模型
class StockIn < ApplicationRecord belongs_to :product end
2. 准备必要的数据库字段
确保Product有quantity字段(默认值设为0,避免nil运算错误),StockIn有amount字段(记录本次入库数量):
Product字段迁移
class AddQuantityToProducts < ActiveRecord::Migration[7.0] def change add_column :products, :quantity, :integer, default: 0, null: false end end
StockIn字段迁移
class AddAmountToStockIns < ActiveRecord::Migration[7.0] def change add_column :stock_ins, :amount, :integer, null: false end end
执行迁移:rails db:migrate
3. 添加模型回调实现自动更新
在StockIn模型中添加after_create回调,创建入库记录后自动累加Product的quantity:
class StockIn < ApplicationRecord belongs_to :product # 创建入库记录后更新产品库存 after_create :update_product_quantity private def update_product_quantity # 用with_lock避免并发更新导致的数据不一致 product.with_lock do product.update!(quantity: product.quantity + amount) end end end
4. (可选)支持修改入库数量时同步调整库存
如果需要允许修改已存在的StockIn记录并同步更新Product库存,添加更新回调:
class StockIn < ApplicationRecord belongs_to :product after_create :update_product_quantity before_update :store_old_amount after_update :adjust_product_quantity private def update_product_quantity product.with_lock do product.update!(quantity: product.quantity + amount) end end # 更新前记录原入库数量 def store_old_amount @old_amount = amount_was end # 根据数量差值调整产品库存 def adjust_product_quantity difference = amount - @old_amount product.with_lock do product.update!(quantity: product.quantity + difference) end end end
5. 配置Rails Admin表单
确保Rails Admin中StockIn的编辑表单能选择Product并输入入库数量:
# config/initializers/rails_admin.rb RailsAdmin.config do |config| config.model StockIn do edit do field :product # 关联选择器 field :amount # 入库数量输入框 # 若有其他字段(如入库日期)可在此添加 end end end
配置完成后,在Rails Admin中创建或修改StockIn记录时,关联的Product的quantity字段会自动同步更新。
内容的提问来源于stack exchange,提问作者Atekelt Afework
相关产品推荐
相关产品推荐

