https://github.com/gilcierweb/CMS-Rails
# app/uploads/galeria_imagem_uploader.rb
class GaleriaImagemUploader < CarrierWave::Uploader::Base
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}#{model.galeria_id}"
end
end
# app/models/adm/galeria_imagem.rb
class Adm::GaleriasImagem < ActiveRecord::Base
belongs_to :galeria, :polymorphic => true
validates :galeria, presence: true
# GaleriasImagem uploader using carrierwave
mount_uploader :imagem, GaleriaImagemUploader
end
# app/models/adm/galeria.rb
class Adm::Galeria < ActiveRecord::Base
has_many :galerias_imagens, :inverse_of => :galeria, :dependent => :destroy
# enable nested attributes for galerias_imagens through galeria class
accepts_nested_attributes_for :galerias_imagens, allow_destroy: true
end
# app/controllers/adm/galerias_controller.rb
class Adm::GaleriasController < ApplicationController
def create
@adm_galeria = Adm::Galeria.new(adm_galeria_params)
respond_to do |format|
if @adm_galeria.save
# to handle multiple images upload on create
if params[:adm_galeria][:imagem]
params[:adm_galeria][:imagem].each { |image|
@adm_galeria.galerias_imagens.create(imagem: image)}
end
format.html { redirect_to @adm_galeria, notice: 'Galeria was successfully created.' }
format.json { render :show, status: :created, location: @adm_galeria }
else
format.html { render :new }
format.json { render json: @adm_galeria.errors, status: :unprocessable_entity }
end
end
end
end
# app/controllers/adm/galerias_imagens_controller.rb
class Adm::GaleriasImagensController < ApplicationController
def create
@adm_galerias_imagem = Adm::GaleriasImagem.new(adm_galerias_imagem_params)
@adm_galerias_imagem.save
end
end