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

Sunday, 10 May 2020

Search other table User Join

if params[:q].blank?
      @admins = Admin.paginate(page: params[:page])
    else
      @admins = Admin.joins(:profile).where(["LOWER(first_name) LIKE ? OR LOWER(last_name) LIKE ?","#{params[:q].downcase}%", "#{params[:q].downcase}%"]).paginate(page: params[:page])

      # @admins = Admin.joins(:profile).where(["LOWER(first_name) LIKE ?","#{params[:q].downcase}%"]).paginate(page: params[:page])
    end
    respond_to do |format|
      format.html { render :index }
      format.js { render :search_users }
    end




def agent_search
    if params[:q].present?
      # @agent_name = agents.joins(:profile).where("profiles.first_name= ? ", params[:q])
      @agent_name = agents.joins(:profile).where(["LOWER(first_name) LIKE ?","#{params[:q].split("=").last.downcase}%"])

      # @agents_skill = agents.joins(:skills).where('skills.name IN(:search)', {search: params[:q]})
      @agents_skill = agents.joins(:skills).where(["LOWER(name) LIKE ?","#{params[:q].split("=").last.downcase}%"])

      @agents = (@agent_name + @agents_skill).uniq
    else
      @agents = agents
    end 
      respond_to do |format|
        format.js { render :agent_search }
      end
  end