Surge Pedroza Surge Pedroza - 5 months ago 6
Ruby Question

How can I combine the code in my Search Model?

I am currently working on Search using this tutorial. Everything works great, and I am able to search for various resources from two different tables (School & District).

However, I am currently calling two separate search methods from my controller, and combining the search results into one array in my controller.

Is there anyway to combine the code in my Model?

Search Controller

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


Method

//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

Answer

Just add a new method to your model:

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

And use it in your controller like this:

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

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