Last Updated: March 02, 2016
·
3.991K
· tmartin314

Rails 4 imageable for multiple models

Using the imageable pattern for storing rails images eliminates dependencies on gems and makes adding more models more manageable.

There are some details about this pattern in the docs: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

Using refile, here's a rough set up:

Generate the Image model:

class CreateImages < ActiveRecord::Migration
  def change
    create_table :images do |t|
      t.string :file_id
      t.boolean :featured
      t.references :imageable, polymorphic: true, index: true
      t.timestamps null: false
    end
  end
end

Update the Image model:

class Image < ActiveRecord::Base
  attachment :file
  belongs_to :imageable, polymorphic: true
end

Add association

class Model < ActiveRecord::Base
  has_many :images, as: :imageable, dependent: :destroy
  accepts_attachments_for :images, attachment: :file
end

Using the fields in the add/edit form (using slim):

There are more details about the refile gem in the docs

.form-group
    = f.attachment_field :images_files, multiple: true, presigned: true, direct: true

Allow the files in the controller strong params:

params.require(:community).permit(:name, :description, :address, :city, :province, :postal_code, :status, images_files: [])

# The important item
images_files: []