Rails:在boostrap导航栏中搜索表单

时间:2016-10-02 08:27:31

标签: ruby-on-rails twitter-bootstrap

我试图将搜索表单添加到bootstrap导航栏中,但没有运气。搜索表单在app / views / searching / new.html.erb中正常运行。当我在app / views / layouts / _header.html.erb中添加相同的搜索表单时,我得到的形式中的第一个参数不能包含nil或为空“'每时每刻。我试图将@search的形式更改为搜索路径,但它们都没有正常工作。 我很欣赏如何使代码更好的任何提示,我觉得我可以用更优雅的方式在搜索模型中编写代码。 谢谢你的帮助。

应用程序/视图/布局/ _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

1 个答案:

答案 0 :(得分:0)

我没有测试过,但应该可以使用。不要忘记将search_path更改为您自己的。{/ p>

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