如何组合搜索模型中的代码?

时间:2016-07-07 19:51:56

标签: ruby-on-rails ruby search

我目前正在使用此tutorial进行搜索。一切都很好,我能够从两个不同的表(学校和区)搜索各种资源。

但是,我目前正在从我的控制器调用两个单独的搜索方法,并将搜索结果合并到我的控制器中的一个数组中。

无论如何要将我的模型中的代码组合起来?

搜索控制器

def show
  @search = Search.find(params[:id])

  @searches = []

  ///Calls two separate search methods from my model and combines the results.
  (@searches << @search.district_resources).flatten!
  (@searches << @search.school_resources).flatten!
  @searches = @searches.uniq

  respond_to do |format|
    format.json { render :json => @searches.to_json }
  end
end

方法

//How can I combine this code to search for values in both tables?
def district_resources
  @district_resources ||= find_district_resources
end

def school_resources
  @school_resources ||= find_school_resources
end

def find_school_resources
  school_resources = SchoolResource.order(:name)
  school_resources = school_resources.where(state_id: state_id) if state_id.present?
end

def find_district_resources
  district_resources = DistrictResource.order(:name)
  district_resources = district_resources.where(state_id: state_id) if state_id.present?
end

1 个答案:

答案 0 :(得分:1)

只需在模型中添加新方法:

def district_and_school_resources
  (district_resources + school_resources).uniq.sort_by(&:name)
end

并在你的控制器中使用它:

def show
  resources = Search.find(params[:id]).district_and_school_resources

  respond_to do |format|
    format.json { render :json => resources.to_json }
  end
end
相关问题