Export data into csv file

Hello,

I am trying to export data from my ruby on rails app to a csv file. The problem is that there are some fields that are encrypted so I need to run a couple of loops... maybe. Can anyone help me with this?

Here's what I have in my model:

def self.to_csv
attributes = %w{ username created_at updated_at first_name last_name email admin user_group.name last_change }
arr = %w{full_name user_groups}

CSV.generate(headers: true) do |csv|
csv.each do field
arr << self.user.send(field) end # pass in attributes as first row csv << attributes User.each do csv << self.attributes.values_at(*attributes) user.send(:first_name) user.send(:full_name) user.send(:last_name) user.send(:user_groups) end end end And this is what I have on my controller: def index @users = User.where(index_filters).page(params[:page]).per(15) respond_to do |format| format.html format.json { render :json => @users }
format.csv {
if current_user.admin?
send_data User.to_csv, filename: "Users-#{Date.today}.csv"
else
flash[:error] = 'Sorry, you do not have the rights to view this file...'
redirect_to root_path
end
}
end
end

Leave a Comment