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

£可爱£侵袭症+ 提交于 2019-12-25 15:55:31

问题


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

回答1:


In your gem file change rails gem to the latest: gem 'rails', '~> 5.1.1' or higher consol: bundle update Restart your rails application Hope this works for you



来源:https://stackoverflow.com/questions/44576663/how-to-fix-undefined-method-form-with-in-my-search-bar-when-building-out-globa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!