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

时间:2014-07-04 01:43:22

标签: ruby-on-rails activerecord ruby-on-rails-4

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

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

syntax error, unexpected '=', expecting keyword_end

#应用程序/控制器/ orders_controller.rb

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

#Purchase Model

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

#products table

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

#purchases表

...
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

1 个答案:

答案 0 :(得分:2)

我还没有对此进行过测试,但我确信它会更新产品并购买 记录你的预期方式。

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