简体   繁体   中英

How to fix undefined method `form_with' in my search bar when building out Global Autocomplete Search?

I get a strange error when trying to run a global autocomplete search across multiple models in my rails App and leveraging the easy-autocomplete jquery library along with the ransack gem for search.

Specifically, I believe the error is in my navbar page as I get this error when I try to run a query- undefined method form_with for #<#<class:0x007f875a6f8b58>:0x007f87600e0aa8>

I decided to hack away and switch form_with for form_tag but then I get an error on the line immediately below undefined method text_field for nil:NilClass" I have listed all my relevant code below. Thank you so much for any help.

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)
});

在您的gem文件中,将rails gem更改为最新的:gem'rails','〜> 5.1.1'或更高版本consol:捆绑包更新重新启动rails应用程序希望这对您有用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM