如何修复未定义的方法`form_with'在构建全局自动填充搜索时,在我的搜索栏中?

时间:2017-06-15 20:40:14

标签: jquery ruby-on-rails search ruby-on-rails-5 ransack

尝试在我的rails应用程序中跨多个模型运行全局自动完成搜索并利用easy-autocomplete jquery库以及用于搜索的ransack gem时,我遇到了一个奇怪的错误。

具体来说,我相信错误发生在我的导航栏页面中,因为当我尝试运行查询时出现此错误 - undefined method form_with for #<#<class:0x007f875a6f8b58>:0x007f87600e0aa8>

我决定攻击并切换form_tag的form_with但是我在undefined method text_field for nil:NilClass"下面的行上出现错误我在下面列出了所有相关代码。非常感谢您的帮助。

Main_Controller.rb

class MainController < ApplicationController
def index
end
def search
@movies    = Movie.ransack(name_cont: params[:q]).result(distinct: true)
@directors = Director.ransack(name_cont: params[:q]).result(distinct: true)

respond_to do |format|
  format.html {}
  format.json {
    @movies    = @movies.limit(5)
    @directors = @directors.limit(5)
  }
end
end
end

_navbar.html.erb

<%= form_with url: search_path, local: true, method: :get, html: { class: "form-inline my-2 my-lg-0" } do |form| %>
  <%= form.text_field :q, placeholder: "Search", data: { behavior: "autocomplete" }, class: "form-control mr-sm-2" %>
  <%= form.button "Search", class: "btn btn-outline-success my-2 my-sm-0" %>
<% end %>

search.html.erb

<div class="row">
<div class="col">
<h1>Movies</h1>
<% @movies.each do |movie| %>
  <p><%= link_to movie.name, movie %></p>
<% end %>
</div>
<div class="col">
<% @directors.each do |director| %>
  <p><%= link_to director.name, director %></p>
<% end %>
</div>
</div>

search.js

document.addEventListener("turbolinks:load", function() {
$input = $("[data-behavior='autocomplete']")
var options = {
getValue: "name",
url: function(phrase) {
  return "/search.json?q=" + phrase;
},
categories: [
  {
    listLocation: "movies",
    header: "<strong>Movies</strong>",
  },
  {
    listLocation: "directors",
    header: "<strong>Directors</strong>",
  }
],
list: {
  onChooseEvent: function() {
    var url = $input.getSelectedItemData().url
    $input.val("")
    Turbolinks.visit(url)
  }
}
}
$input.easyAutocomplete(options)
});

1 个答案:

答案 0 :(得分:5)

在你的宝石文件中,将rails gem更改为最新的:gem&#39; rails&#39;,&#39;〜&gt; 5.1.1&#39;或更高 consol:捆绑更新 重启rails应用程序 希望这对你有用