![](/img/trans.png)
[英]How do I force rails to update `updated_at` and run callbacks, even if the record hasn't been changed
[英]How do I update an object that hasn't been saved without saving it?
所以我這樣做:
@portfolio = current_user.portfolio
@port_stock = PortStock.new(port_stock_params)
stock = Stock.find(port_stock_params[:stock_id])
@port_stock.update!(current_price: stock.price)
respond_to do |format|
if @port_stock.save
我遇到的問題是,當我致電.update!
在@port_stock
它實際上將記錄保存在@port_stock.save
之后。
所以我的回調被執行了兩次,這弄亂了我數據庫中的內容。
那么,如何在顯式調用@port_stock.current_price
的new
實例而不實際保存@port_stock
對象的情況下呢?
謝謝。
如果僅更新一個屬性,則可以使用setter:
@port_stock.current_price = stock.price
或者您可以這樣做:
stock = Stock.find(port_stock_params[:stock_id])
@port_stock = PortStock.new(port_stock_params.merge(current_price: stock.price))
試試assign_attributes
,它接受一個哈希作為參數並且不打數據庫,它只對對象起作用
@port_stock.assign_attributes(current_price: stock.price)
顯然,如果只想更新一個字段,@ Sergio的答案會更好,更簡單
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.