.each 遍历空集合 - Ruby on Rails

.each iterates over empty collection - Ruby on Rails

我有一个名为 Attachment 的多态模型。我正在使用 gem Carrierwave 来保存附件。

在我的 Customer 编辑页面上,我执行以下代码:

    puts @customer.attachments.count
    @customer.attachments.each do |i|
        puts i.id #outputs a blank line 
    end

puts @customer.attachments.count 输出 0。但是,迭代器仍然对附件运行 1 次并打印出一个空行来代替 puts i.id

这是我的模型:

class Attachment < ApplicationRecord
    mount_uploader :attachment, AttachmentUploader # Tells rails to use this uploader for this model.
    validates :name, presence: true

    belongs_to :attachable, :polymorphic => true
    belongs_to :account
end

模型将加载它们的关联一次,例如@customer.attachments,然后不再查询它们。如果关联发生变化,@customer.attachments 将过时。例如...

# Let's say this includes Attachment 123
puts @customer.attachments

Attachment.delete(123)

# Will still include Attachment 123
puts @customer.attachments

您可以手动卸载与 @customer.attachments.reset forcing it to be reloaded next time. Better is to change the association in a manner which the association is aware of, such as calling destroy on the association itself 的关联。

@customer.attachments.destroy( Attachment.find(123) )

这将同时删除附件 123 并将其从 @customer.attachments 中删除。

与创建协会类似的问题。这将创建附件并更新 @customer.attachments.

puts @customer.attachments

Attachment.create( foo: "bar", customer: @customer )

# will not be aware of the new Attachment.
puts @customer.attachments

和以前一样,在关联上调用 create

@customer.attachments.create( foo: "bar" )

这也有很好的效果,可以为您填写正确的客户,避免可能出现的错误。并且它避免在整个代码中重复附件 class 名称,使代码变干。