Skip to content

Instantly share code, notes, and snippets.

@willsza
Last active August 29, 2015 14:16
Show Gist options
  • Save willsza/f74828c71c5aac557eba to your computer and use it in GitHub Desktop.
Save willsza/f74828c71c5aac557eba to your computer and use it in GitHub Desktop.
Criando uma action para importação de arquivos CSV
= simple_form_for @mailing, :url => import_mailings_path, multipart: true do |f|
= f.error_notification
.form-inputs
= f.input :file, as: :file
.form-actions
= f.button :submit, "Enviar Arquivo", class: 'btn btn-primary'
h1 Listar Contatos
hr
table.table.table-striped
thead
tr
th Email
th Empresa
th
tbody
- @mailings.each do |mailing|
tr
td = mailing.email
td = mailing.company
td
.btn-group.pull-right
= link_to 'Ver', mailing, class: 'btn btn-default btn-sm'
= link_to 'Editar', edit_mailing_path(mailing), class: 'btn btn-default btn-sm'
= link_to 'Excluir', mailing, data: {:confirm => 'Tem certeza?'}, :method => :delete, class: 'btn btn-default btn-sm'
= link_to 'Novo Contato', new_mailing_path, class: 'btn btn-primary'
hr
h4 Importar Lista
== render 'form_import'
class Mailing < ActiveRecord::Base
belongs_to :company
has_one :profile
attr_accessor :file
validates :email, presence: true
validates :email, uniqueness: true
def self.import(file)
CSV.foreach('file', headers: true) do |row|
Mailing.create! row.to_hash
end
end
end
class MailingsController < ApplicationController
before_action :set_mailing, only: [:show, :edit, :update, :destroy]
# GET /mailings
def index
@mailings = Mailing.all
@mailing = Mailing.new
end
# GET /mailings/1
def show
end
# GET /mailings/new
def new
@mailing = Mailing.new
end
# GET /mailings/1/edit
def edit
end
# POST /mailings
def create
@mailing = Mailing.new(mailing_params)
if @mailing.save
redirect_to mailings_path, notice: 'Mailing was successfully created.'
else
render :new
end
end
# PATCH/PUT /mailings/1
def update
if @mailing.update(mailing_params)
redirect_to @mailing, notice: 'Mailing was successfully updated.'
else
render :edit
end
end
# DELETE /mailings/1
def destroy
@mailing.destroy
redirect_to mailings_url, notice: 'Mailing was successfully destroyed.'
end
def import
Mailing.import(params[:file])
redirect_to mailings_path, notice: "Contatos importados."
end
private
# Use callbacks to share common setup or constraints between actions.
def set_mailing
@mailing = Mailing.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def mailing_params
params.require(:mailing).permit(:email, :company_id)
end
end
Rails.application.routes.draw do
resources :mailings do
collection { post :import }
end
resources :profiles
resources :companies
root 'companies#index'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment