Last Updated: March 02, 2016
· 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:

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

Update the Image model:

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

Add association

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

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

There are more details about the refile gem in the docs

    = 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: []