Tuesday, 19 May 2020

Export csv in rails with other table

Application.rb

require "csv"

========================================================
Controller:

def index
    if params[:q].blank?
      @clients = Client.order("client_id ASC").paginate(page: params[:page])
    else
      @clients = Client.joins(:profile).where(["LOWER(first_name) LIKE ? OR LOWER(last_name) LIKE ?","#{params[:q].downcase}%", "#{params[:q].downcase}%"]).paginate(page: params[:page])
    end
    respond_to do |format|
      format.html { render :index }
      format.js { render :search_users }


      format.csv { send_data @clients.to_csv, filename: "Filename.csv" }

    end
   
  end


======================================================
On model:


def self.to_csv
    CSV.generate(headers: true) do |csv|
      csv << ["Id", "Email", "First Name", "Last Name"]

      all.each do |user|
        row = [user.id, user.email, user.profile.first_name, user.profile.last_name]
        csv << row
      end
    end
  end

No comments:

Post a Comment