import export method
controller ::
def import
csv_data = BxBlockFee::Fee.import(params[:file])
render json: {message: "Fee data is successfully Imported"}, status: :created
end
def export
csv_data = BxBlockFee::Fee.all
respond_to do |format|
format.csv { send_data csv_data.to_csv, filename: "Installment-#{DateTime.now}.csv" }
end
end
route ::
namespace :bx_block_fee do
resources :fees, :only => [:index, :create, :update, :show, :destroy] do
post 'import', on: :collection
get 'export', on: :collection
end
end
model ::
module BxBlockFee
class Fee < BxBlockFee::ApplicationRecord
require 'csv'
self.table_name = :fees
validates :name, :valid_until, :amount, presence: true
belongs_to :academic_account, class_name: "BxBlockAcademicAccount::AcademicAccount"
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
Fee.create! row.to_hash
end
end
def self.to_csv
attributes = %w{id name valid_until academic_account_id amount }
CSV.generate(headers: true) do |csv|
csv << attributes
all.each do |fee|
csv << attributes.map{ |attr| fee.send(attr) }
end
end
end
end
end
Comments
Post a Comment