2016-07-07 6 views
0

私は現在、この検索を使って検索していますtutorial。すべてがうまくいき、2つの異なるテーブル(School &地区)からさまざまなリソースを検索できます。検索モデルでコードを組み合わせるにはどうすればよいですか?

しかし、私は現在、私のコントローラから2つの別個の検索メソッドを呼び出し、検索結果を自分のコントローラの1つの配列に結合しています。

私のモデルにコードを組み合わせるのにとにかくありますか?

検索コントローラー

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 
+2

2つのモデルはどのように関連していますか? STIを使用していますか? – oreoluwa

答えて

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 
関連する問題