简体   繁体   English

如果每条记录为零,Rails 会更新多条记录

[英]Rails update multiple records if each record is nil

I want to update record in one, single shot to db when published_at is nil instead of two:published_at为 nil 而不是两个时,我想一次性更新记录到 db:

  portfolio_report.update!(published: true)
  portfolio_report.update!(published_at: DateTime.current) if portfolio_report.published_at.nil?

Is it possible to have something like:是否有可能有类似的东西:

  portfolio_report.update!(
    published: true,
    published_at: DateTime.current if nil?
  )

You have a couple of options here actually.实际上,您有几个选择。 Maybe the one that answers your question most directly is:也许最直接回答您的问题的是:

portfolio_report.update!(
  published: true,
  published_at: portfolio_report.published_at || DateTime.current
)

(This assumes published_at has not been updated from another thread and made this in-memory instance stale, but it matches the behaviour of the original example, so I assume that is not a problem.) (这假设published_at没有从另一个线程更新,并使这个内存中的实例过时,但它与原始示例的行为相匹配,所以我认为这不是问题。)

You could also accomplish the same thing with a before_update callback, but that would both be more indirect and require more code.您也可以使用before_update回调来完成同样的事情,但这会更加间接并且需要更多代码。

Either way, it's probably a good idea to encapsulate this in a method on your PortfolioReport model:无论哪种方式,将其封装在您的PortfolioReport model 上的方法中可能是个好主意:

class PortfolioReport < ApplicationRecord
  def publish!
    update!(
      published: true,
      published_at: published_at || DateTime.current
    )
  end
end

This way every call site does not need to remember to get this right.这样,每个呼叫站点都不需要记住正确执行此操作。

You can use where to limit it and make one line.您可以使用 where 限制它并制作一条线。

portfolio_report.where(published_at: nil).update!(published_at: DateTime.current, published: true)

You can add data to record and after save it.您可以添加数据以记录并保存后。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM