Skip to content

Instantly share code, notes, and snippets.

@sheharyarn
Last active January 18, 2021 15:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sheharyarn/a8a0b1990e157b0f18c1a4b95f704334 to your computer and use it in GitHub Desktop.
Save sheharyarn/a8a0b1990e157b0f18c1a4b95f704334 to your computer and use it in GitHub Desktop.
Polymorphic Paperclip class with unique partial ActiveRecord index on :default_image
# db/migrations/xxxxxxxxxxxxxx_create_image_attachment.rb
class CreateImageAttachments < ActiveRecord::Migration[5.0]
def change
create_table :image_attachments do |t|
t.belongs_to :imageable, polymorphic: true
t.attachment :data
t.boolean :default, default: false
t.timestamps
end
add_index :image_attachments, [:imageable_id, :imageable_type, :default], unique: true, where: '"default" = TRUE', name: :unique_on_imageable_default
end
end
# app/models/image_attachment.rb
class ImageAttachment < ApplicationRecord
belongs_to :imageable, polymorphic: true
has_attached_file :data,
styles: { thumb: '120x120#', medium: '600x600>' },
convert_options: { thumb: '-quality 75 -strip', medium: '-quality 90 -strip' }
validates_attachment_presence :data
validates_attachment_size :data, less_than: PAPERCLIP_IMAGE_SIZE_LIMIT
validates_attachment_content_type :data, content_type: PAPERCLIP_IMAGE_CONTENT_TYPE
validates :default, uniqueness: { scope: :imageable }, if: :default?
def undefault!
update(default: false)
end
def default!
imageable.default_image.undefault! if imageable.default_image
update(default: true)
end
end
# app/models/concerns/imageable.rb
module Imageable
extend ActiveSupport::Concern
included do
has_many :image_attachments, as: :imageable, dependent: :destroy
alias_attribute :images, :image_attachments
end
def default_image
images.find_by(default: true)
end
end
@wolfstain
Copy link

I dont understand how it works, I tried to implement this code but its not saving the attached file, i dont understand why :/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment