angkiki
angkiki

Reputation: 495

Controller logic for multiple filters

I have the following methods defined in my tutor.rb model

def self.fees_search(n)
    @profile = Profile.fees_to(n)
    if @profile.empty?
      return Tutor.none
    else
      @profile.map do |y|
        y.tutor
      end
    end
  end

  def self.subject_search(s)
    @subject = Subject.find_by_name(s)
    unless @subject.nil?
      @subject.tutors 
    end
  end

And in my tutors_controller.rb i have the following for

def index
    @tutor = Tutor.all
    @tutor = @tutor.fees_search(params[:fees_search]) if params[:fees_search].present?
    @tutor = @tutor.subject_search(params[:subject_search]) if params[:subject_search].present?
  end

The searches both work when applied independently, but when i try to do both, i get the error undefined methodsubject_search' for #now i suppose its because the first method offees_search` would be processed first? Thats why i think i'm getting this error. How should i code my controller action differently then? To accept both filters?

Greatly appreciate all advice. Thanks!

Upvotes: 0

Views: 40

Answers (1)

Sravan
Sravan

Reputation: 18647

Try giving the condtions of what params are present,

def index
    @tutor = Tutor.all

    @tutor_array = []

    @tutor_array << @tutor.fees_search(params[:fees_search]) if (params[:fees_search].present?

    @tutor_array << @tutor.subject_search(params[:subject_search]) if (params[:subject_search].present?

    @tutor_array << @tutor.location_search(params[:location_search]) if (params[:location_search].present?

   @tutor_array.each do |tutor| 
     ids = @tutor.merge(tutor).map(&:id) 
     @tutor = Tutor.where(id: ids) 
   end

end 

Here is the reference

Upvotes: 1

Related Questions