多个过滤器的控制器逻辑

时间:2016-10-06 05:06:36

标签: ruby-on-rails

我在tutor.rb模型中定义了以下方法

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

tutors_controller.rb我的

中有以下内容
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

搜索在独立应用时都有效,但是当我尝试同时执行这两项操作时,我会首先处理错误undefined method subject_search'#now i suppose its because the first method of fees_search`?这就是为什么我认为我得到这个错误。我应该如何编码我的控制器动作呢?接受这两个过滤器?

非常感谢所有建议。谢谢!

1 个答案:

答案 0 :(得分:1)

尝试给出params为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