.each遍历空集合-Ruby on Rails

时间:2018-07-20 17:11:16

标签: ruby-on-rails ruby ruby-on-rails-5 carrierwave

我有一个名为Attachment的多态模型。我正在使用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

1 个答案:

答案 0 :(得分:2)

模型将一次加载其关联,例如@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手动卸载关联,强制下次重新关联。更好的方法是以关联知道的方式更改关联,例如调用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" )

这也具有为您填充正确的客户的良好效果,避免了可能的错误。而且避免了在整个代码中都重复附件类名称,从而使代码成为DRY。