2015-07-03 31 views
1

我有一個類似的問題this,但仍然無法弄清楚。Rails多個form_tag路徑/執行全局搜索

我正在創建一個鏈接到Neo4j數據庫的rails應用程序,並且我想用一個搜索表單搜索多個模型。我正在使用彈性搜索。

我一個模型中搜索當前的代碼(正常工作):

#/app/views/symptoms/index.html 
<%=form_tag symptoms_path, class: "form-inline", method: :get do %> 
    <div class="form-group"> 
    <%= text_field_tag :query, params[:query], class: "form-control" %>  
    <%= submit_tag "Search", class: "btn btn-primary" %> 
    <% if params[:query].present? %>  
    <%= link_to "clear" %> 
    <% end %> 
    </div> 
    <% end %> 

#/app/controllers/symptoms_controller.rb 
def index 
    if params[:query].present? 
    @symptoms = Symptom.search(params[:query], show: params[:show]) 
    else 
    @symptoms = Symptom.all 
    end 
end 

目前這隻會症狀模型中進行搜索。我想要創建一個「全局搜索」字段,該字段將在symptoms_path,allergies_path和drugs_path中進行搜索。

潛力 '全局搜索' 碼:

#/app/views/global_search/index.html 
<%=form_tag [symptoms_path, allergies_path, drugs_path], class: "form-inline", method: :get do %> 
    <div class="form-group"> 
    <%= text_field_tag :query, params[:query], class: "form-control" %>  
    <%= submit_tag "Search", class: "btn btn-primary" %> 
    <% if params[:query].present? %>  
    <%= link_to "clear" %> 
    <% end %> 
    </div> 
    <% end %> 

#/app/controllers/symptoms_controller.rb 
def index 
    if params[:query].present? 
     @allergies = Allergy.search(params[:query], show: params[:show]) 
     @drugs = Drug.search(params[:query]) 
     @symptoms = Symptom.search(params[:query]) 
    else 
     @allergies = Allergy.all 
     @drugs = Drug.all 
     @symptoms = Symptom.all 
    end 
end 

對我怎麼能實現這個任何想法?提前致謝!

回答

1

我可能會建議你創建類似「search_controller」的東西(rails generate controller search應該可以幫助你做到這一點)。在那裏,你可以有一個index行動(或者任何你想打電話給你的動作),然後你只需設置一個路由到一個URL指向它像這樣:

# config/routes.rb 
    # Link the URL to the search controller's `index` action 
    post '/search/:query' => 'search#index' 

# app/controllers/search_controller.rb 

    def index 
    if params[:query].present? 
     @allergies = Allergy.search(params[:query], show: params[:show]) 
     @drugs = Drug.search(params[:query]) 
     @symptoms = Symptom.search(params[:query]) 
    else 
     @allergies = Allergy.all 
     @drugs = Drug.all 
     @symptoms = Symptom.all 
    end 
    end 

很抱歉,如果我誤解,我不確定你在使用Rails之前已經工作了多少,在

+0

之前沒有太多,我在過去幾個月裏一直在教導自己。但是你又一次挽救了這一天,這正是我所期待的。再次感謝,Brian! – Chris

+0

很高興聽到它;)我知道它可能有點令人困惑,因爲例子通常有控制器只圍繞模型旋轉。 –

+0

是的,我花了一點才明白這個概念,有很多樂趣啊!瞬間:) – Chris