我想添加搜索表單到bootstrap導航欄沒有運氣。搜索表單在app/views/searches/new.html.erb中正常工作。當我在app/views/layouts/_header.html.erb中添加相同的搜索表單時,我得到'表單中的第一個參數始終不能包含零或爲空。我試圖將表單中的@搜索更改爲搜索路徑,但沒有一個能夠正常工作。 我會很感激任何提示如何使代碼更好,我覺得我可以用更優雅的方式在搜索模型中編寫代碼。 謝謝你的幫助。Rails:搜索表單在boostrap導航欄
應用程序/視圖/佈局/ _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
當你得到那個錯誤後,點擊或之前? – 7urkm3n
@ 7urkm3n我在嘗試打開我的網站時得到它,我的意思是當我打開本地主機時看到的第一件事是該錯誤 –