Last active
January 18, 2021 15:13
-
-
Save sheharyarn/a8a0b1990e157b0f18c1a4b95f704334 to your computer and use it in GitHub Desktop.
Polymorphic Paperclip class with unique partial ActiveRecord index on :default_image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I dont understand how it works, I tried to implement this code but its not saving the attached file, i dont understand why :/