2016-10-02 9 views
0

私は運のないbootstrap navbarに検索フォームを追加しようとしています。検索フォームはapp/views/searches/new.html.erbで正常に動作します。 app/views/layouts/_header.html.erbに同じ検索フォームを追加すると、「フォームの最初の引数にはnilを含めることはできません。私はフォームで@searchを変更してパスを検索しようとしましたが、どれも正しく動作しません。 コードをより良くするためのヒントを教えていただければ幸いです。よりエレガントな方法でコードを検索モデルに書いたような気がします。 ありがとうございます。Rails:boostrap navbarの検索フォーム

アプリ/ビュー/レイアウト/ _header.html.erb

<%= form_for @search, html: {class: "navbar-form navbar-left"} do |f| %> 
<div class="input-group searchbar"> 
<%= f.text_field :keywords, class: "form-control", placeholder: "Search" %> 
    <span class="input-group-addon"> 
    <%= button_tag(:class => "white") do %> 
    <i class="glyphicon glyphicon-search"></i> 
    <% end %> 
    </span> 
    </div> 
<% end %> 

検索モデル

def questions 
@questions = find_questions 
end 

def answers 
@answers = find_answers 
end 

def users 
@users = find_users 
end 

private 

def find_questions 
questions = Question.order(created_at: :desc) 
questions = questions.where("title like ? OR content like?", "%#{keywords}%", "%#{keywords}%") if keywords.present? 
questions 
end 

def find_answers 
answers = Answer.order(created_at: :desc) 
answers = answers.where("content like ?", "%#{keywords}%") if keywords.present? 
answers 
end 

def find_users 
users = User.order(:username) 
users = users.where("username like ?", "%#{keywords}%") if keywords.present? 
users 
end 

検索コントローラ

def new 
@search = Search.new 
end 

def create 
@search = Search.create!(allowed_params) 
redirect_to @search 
end 

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

private 

def allowed_params 
params.require(:search).permit! 
end 

質問コントローラ - 私は答えで同じコードを持っていますユーザーコントローラー

def index 
@questions = Question.all 
if params[:search] 
    @questions = Question.search(params[:search]) 
end 
end 

ルート

searches GET  /searches(.:format)      searches#index 
     POST  /searches(.:format)      searches#create 
new_search GET /searches/new(.:format)     searches#new 
edit_search GET /searches/:id/edit(.:format)    searches#edit 
search GET  /searches/:id(.:format)     searches#show 
     PATCH /searches/:id(.:format)     searches#update 
     PUT  /searches/:id(.:format)     searches#update 
     DELETE /searches/:id(.:format)     searches#destroy 
root GET /          home#index 
+0

クリックするとエラーが表示されます。 – 7urkm3n

+0

@ 7urkm3n私は私のウェブサイトを開こうとすると、私は私がlocalhostを開くときに表示される最初のことを意味するエラーが発生する –

答えて

0

私がテストしていませんが、それが動作するはずです。 search_pathをあなた自身のものに変更することを忘れないでください。

<%= form_tag ###search_path, method: :get do %> 
    <%= text_field_tag 'keywords', nil, placeholder: "Search", class: "form-control" %> 
    <%= submit_tag 'Search', name: nil %> 
<% end %> 
+0

ありがとう、あなたの助けをたくさん! –