如何检查是否有**已保存**关联记录而不是**内存中**关联记录

How to check whether there are **saved** associated records rather than **in-memory** associated records

我有两个关联模型:

class HelpRequest < ActiveRecord::Base
  has_many :donation_items, dependent: :destroy

class DonationItem < ActiveRecord::Base
  belongs_to :help_request

我有一个验证器,如果 he/she 试图保存没有 donation_items.

help_request,则 returns 给用户一个错误
validate :has_donation_items?
...
def has_donation_items?
  if !self.donation_items.present?
    errors.add :a_help_request, "must have at least one item."
  end
end

不过,这是在保存之前检查当前内存中的状态。但是,我有一个需要,当重新渲染表单时,即使 help_request 有未保存的 donation_item 来测试是否有 [=14= 的已保存 donation_items ].

有没有一种方法可以测试 saved 关联的 donation_items 而不必 遍历每个内存中的 donation_item 并测试是否是新记录?

我希望有像这样简单的(显然是虚构的)示例:

@help_request.saved_donation_items.present?

使用收集和任何? 这确实在你的项目中循环,但它相当简洁

@help_request.donation_items.collect{|di| di.persisted?}.any?

或者再打数据库(假设help_request已经保存)

HelpRequest.find(@help_request.id).donation_items.any?