javaeye3/lib/attachable_model.rb

20 lines
674 B
Ruby

module AttachableModel
def self.included(model)
model.has_many :attachments, :foreign_key => "attach_to_id", :conditions => "attach_type = '#{model.class_name}'"
end
def attach!(owner = :user)
user = owner.is_a?(User) ? owner : self.send(owner)
return unless user
orphan_attachments = user.orphan_attachments
unless orphan_attachments.empty?
Attachment.update_all(["attach_to_id = ?, attach_type = ?", self.id, self.class.name], ['id in (?)', orphan_attachments.map(&:id)])
self.update_attribute(:attach, true) if self.has_attribute?(:attach)
end
end
def none_image_attachments
attachments.select{|a| !a.image?}
end
end