Skip to main content
 首页 » 编程设计

ruby-on-rails中Rails 4中更新多个表条目中产品和延期交货

2025年01月19日10myhome

当用户购买产品时,我需要调整产品的库存(product.stock)。如果用户想要的数量大于可用数量,那么我想在 product.backorder 中存储我必须订购的数量。

以下模型中的代码是我提出的对我来说有意义的算法,但是当我添加 :backorder = :backorder + amount.abs 时,我在 Controller 中收到以下错误和 :stock = 0。这些变量是产品表的一部分,也许我无法从购买模型中写入它们?

语法错误,意外的“=”,需要关键字_end

#app/controllers/orders_controller.rb

def show 
  @order = Order.find(params[:id]) 
  @purchases = @order.purchases #this line is highlighted 
end 

#购买模式

class Purchase < ActiveRecord::Base 
    #... other code 
    belongs_to :product 
 
 after_create :adjust_inventory 
 
 def adjust_inventory 
    amount = :stock - quantity 
 
    unless amount < 0 
        product.decrement!(:stock, quantity) 
    else 
        backordered = amount.abs 
        :backorder = :backorder + amount.abs 
        :stock = 0 
        product.save 
        purchase.save 
    end 
 end 
end 

#产品表

... 
t.string   "name" 
t.decimal  "price" 
t.integer  "stock" 
t.integer  "backorder" 

#购买表

... 
t.string   "name" 
t.integer  "quantity" # amount client would like to purchase 
t.decimal  "price" 
t.integer  "backordered" # amount to restock and give to the client 

请您参考如下方法:

我还没有测试过这个,但我很确定它会更新产品和购买 按照您想要的方式记录。

class Purchase < ActiveRecord::Base 
  belongs_to :product 
 
  after_create :adjust_inventory 
 
  def adjust_inventory 
    amount = product.stock - quantity 
 
    unless amount < 0 
      product.decrement!(:stock, quantity) 
    else       
      product.update( 
        backorder:  (product.backorder || 0) + amount.abs, 
        stock: 0 
      ) 
 
      self.backordered = amount.abs 
      save 
    end 
  end 
end