我正在努力使我的模型回调函数正常运行:(使用Rails 5.2.4.1,Ruby 2.6.3和pg〜> 0.21
我有一个模型“批次”,一旦其“价格”和“数量”值大于零,我就希望自动计算并更新其自己的“值”属性。
def change
create_table :batches do |t|
t.references :product, foreign_key: true, null: false
t.references :currency, foreign_key: true
t.string :batch_number, null: false
t.string :status, null: false, default: "pending"
t.integer :quantity, null: false, default: 0
t.integer :price, null: false, default: 0
t.integer :value, null: false, default: 0
t.timestamps
end
end
end
在我的种子文件中,创建了一些批处理实例,这些批处理实例具有指定的数量和价格,然后将其默认值保留为0(稍后在创建订单实例时将其添加):
batch1 = Batch.new(
product_id: Product.last.id,
batch_number: "0001-0001-0001",
quantity: 1800
)
if batch1.valid?
batch1.save
p batch1
else
p first_batch1.errors.messages
end
batch1.price = 3
batch1.save
然后我的烦恼开始了...我尝试了几种类似于以下的方法:
after_find :calculate_value
def calculate_value
self.value = price * quantity if value != price * quantity
end
我不确定在这里是否遗漏了一些非常明显的东西,但是值似乎从未更新。
我已经尝试将save添加到方法中,但它似乎也不起作用。我发现保存在这些回调中的其他一些行为非常奇怪。
例如,我使用此实例方法通过联接表将货币分配给批次:
after_find :assign_currency
def assign_currency
self.currency_id = currency.id unless currency.nil?
# save
end
如果取消注释“保存”(或将其设置为“ self.save”),则种子文件创建批处理,但随后无法创建联接表,返回{:batch => [“必须存在”]]}。但是在控制台中,该批处理确实可以:
[#<Batch:0x00007fb874ad0aa0
id: 1,
product_id: 1,
batch_number: "0001-0001-0001",
status: "pending",
quantity: 1800,
currency_id: nil,
price: 0,
value: 0,
created_at: Thu, 09 Jan 2020 00:38:42 UTC +00:00,
updated_at: Thu, 09 Jan 2020 00:38:42 UTC +00:00>,
我仍然对Rails还是陌生的,因此非常感谢任何建议!感觉应该很简单,这让我发疯了...
在您的模型中如何?
after_find :calculate_value
def calculate_value
self.value = self.price * self.quantity if self.value != self.price * self.quantity
end