代码之家  ›  专栏  ›  技术社区  ›  Cannon Moyer

.each遍历空集合-ruby on rails

  •  0
  • Cannon Moyer  · 技术社区  · 8 年前

    我有一个多态模型叫做 Attachment 是的。我在用宝石夹来保存附件。

    关于我的 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 回复  |  直到 8 年前
        1
  •  2
  •   Schwern    8 年前

    模型将加载其关联一次,例如 @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并将其从 @客户附件 是的。

    创建关联的类似问题这将创建附件并更新 @客户附件 是的。

    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" )
    

    这也有一个很好的效果,为您填写正确的客户,避免了可能的错误。它避免了在代码中重复附件类名,从而使代码变干。