我有一个名为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
模型将加载其关联一次,例如@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
。
@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" )
这也具有为您填写正确客户的良好效果,避免了可能的错误。它避免了在整个代码中重复附件类名,使代码变得干燥。