Skip to content

Instantly share code, notes, and snippets.

@jameslafa
Created July 17, 2013 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jameslafa/6021470 to your computer and use it in GitHub Desktop.
Save jameslafa/6021470 to your computer and use it in GitHub Desktop.
Add multiple images to a model using Paperclip and active_admin
ActiveAdmin.register Project do
controller do
def permitted_params
params.permit project: [:title, :summary, :description, :thumbnail, :date, :url, :client_list, :technology_list, :type_list, :images_attributes => [:picture, :id, :_destroy]]
# to add unlimited :image, you need to permit :images_attributes => [:picture, :id, :_destroy]
# - picture for the image
# - id to avoid duplicates
# - _destroy if you want to allow image delete
end
end
form do |f|
f.inputs "Project Details" do
f.input :title
f.has_many :images do |p|
p.inputs do
p.input :_destroy, :as => :boolean, :label => "Destroy?" unless p.object.new_record?
# add a _destroy field if this is an existing record (don't forget to permit this field)
p.input :picture, :as => :file, :hint => p.object.new_record? ? "" : f.template.image_tag(p.object.picture.url(:thumb))
# add a new picture and display the image if the picture already exists
end
end
end
f.actions
end
show do |ad|
attributes_table do
row :title
# Loop on every existing images and display them in a list
row :images do
ul do
ad.images.each do |img|
li do
image_tag(img.picture.url(:thumb))
end
end
end
end
end
end
end
class CreateImages < ActiveRecord::Migration
def change
create_table :images do |t|
t.belongs_to :project
t.attachment :picture
t.timestamps
end
end
end
class Image < ActiveRecord::Base
belongs_to :project
has_attached_file :picture, :styles => { :large => "960x640>", :medium => "300x300>", :thumb => "150x150>" }, :default_url => "/images/:style/missing.png"
end
class Project < ActiveRecord::Base
# Add multiple images
has_many :images, :dependent => :destroy
accepts_nested_attributes_for :images, :allow_destroy => true
# don't forget allow_destroy to be able to delete images through Project
end
@jameslafa
Copy link
Author

If you have an error new_record? method does not exists, you probably forgot to add accepts_nested_attributes_for in your model.

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