3
\$\begingroup\$

I have this really really long controller action and would like someone to help me break it down.

  def index
    @credit_unions = Company.parent_with_branches

    @loan_officers = []

    @loan_requests = LoanRequest.includes(:dealer, :loan_officer, :branch => :parent)
    if params[:query].present?
      results = @loan_requests.search(params[:query]).results
      @loan_requests = LoanRequest.where(id: results.map(&:id))
    end

    if params.include? 'filter'

      if params[:filter][:branch_id].present? && params[:filter][:branch_id].reject!(&:blank?).present?
        @loan_requests = @loan_requests.where(:branch_id => params[:filter][:branch_id])
        @loan_officers = LoanOfficer.where(:company_id => params[:filter][:branch_id])
      end

      if params[:filter][:loan_officer_id].present?
        @loan_requests = @loan_requests.where(:loan_officer_id => params[:filter][:loan_officer_id])
      end

      if params[:filter][:reward_type].present?
        @loan_requests = @loan_requests.where(reward_type: params[:filter][:reward_type])
      end

      if params[:filter][:transaction_type].present?
        @loan_requests = @loan_requests.where(transaction_type: params[:filter][:transaction_type])
      end

      if params[:filter][:status].present?
        @loan_requests = @loan_requests.where(:status => params[:filter][:status])
      end

      if params[:filter][:start_date].present?
        start_date = Date.strptime(params[:filter][:start_date], '%m/%d/%Y').beginning_of_day
        @loan_requests = @loan_requests.where('printed_at >= ?', start_date)
      end

      if params[:filter][:end_date].present?
        end_date = Date.strptime(params[:filter][:end_date], '%m/%d/%Y').end_of_day
        @loan_requests = @loan_requests.where('printed_at <= ?', end_date)
      end
    end

    respond_to do |format|
      format.html do
        @q = @loan_requests.ransack(params[:q])
        @loan_requests = @q.result.paginate(:page => params[:page], :per_page => 50)
        @loan_requests = @loan_requests.order(created_at: :desc)
      end
    end
  end
\$\endgroup\$
  • 2
    \$\begingroup\$ I am too lazy to write this again :) stackoverflow.com/a/4480285/188031 \$\endgroup\$ – tokland Feb 4 '16 at 18:34
  • 1
    \$\begingroup\$ The best approach would be Passive controller with services \$\endgroup\$ – Nermin Feb 6 '16 at 17:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.