[英]Rails update multiple records if each record is nil
當published_at
為 nil 而不是兩個時,我想一次性更新記錄到 db:
portfolio_report.update!(published: true)
portfolio_report.update!(published_at: DateTime.current) if portfolio_report.published_at.nil?
是否有可能有類似的東西:
portfolio_report.update!(
published: true,
published_at: DateTime.current if nil?
)
實際上,您有幾個選擇。 也許最直接回答您的問題的是:
portfolio_report.update!(
published: true,
published_at: portfolio_report.published_at || DateTime.current
)
(這假設published_at
沒有從另一個線程更新,並使這個內存中的實例過時,但它與原始示例的行為相匹配,所以我認為這不是問題。)
您也可以使用before_update
回調來完成同樣的事情,但這會更加間接並且需要更多代碼。
無論哪種方式,將其封裝在您的PortfolioReport
model 上的方法中可能是個好主意:
class PortfolioReport < ApplicationRecord
def publish!
update!(
published: true,
published_at: published_at || DateTime.current
)
end
end
這樣,每個呼叫站點都不需要記住正確執行此操作。
您可以使用 where 限制它並制作一條線。
portfolio_report.where(published_at: nil).update!(published_at: DateTime.current, published: true)
您可以添加數據以記錄並保存后。
portfolio_report.published = true
portfolio_report.published_at = DateTime.current if portfolio_report.published_at.nil?
portfolio_report.save!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.