0

I am trying to use an autocomplete function for when the user attempts to enter in an license plate number into the appropriate rails form. I've been going through easyautocomplete and jquery-ui autocomplete. However can't seem to get any of them to work because the license_number attribute is a nested attribute and I can't find a way to get it all associated.

permit.rb

class Permit < ApplicationRecord
self.primary_key = :permit_id
has_one :vehicle
accepts_nested_attributes_for :vehicle

vehicle.rb

class Vehicle < ApplicationRecord
self.primary_key = :vehicle_id
belongs_to  :permit, optional: true

permit form

<%= form_with(model: permit, local: true) do |form| %>
...
<div class="field">
  <%= form.fields_for :vehicle do |f| %>
    <%= f.label :license_number %>
    <%= f.text_field :license_number %>
  <% end %>
</div>
...

The vehicle model has a attribute called license_number. How do I grab all of the license numbers from that model and get it associated so I can use an autocomplete function?

edit

permits.coffee

jQuery ->
$('#vehicle_license_number').autocomplete
    source: vehicle.collect( |car| [car.license_number, car.vehicle_id])
2
  • Please provide your JavaScript code that is being used for autocomplete. Most likely you will need to use source as a function, where you can custom search for nested element versus top element. Also include an example of the data.
    – Twisty
    Commented Nov 16, 2017 at 17:46
  • Forgot about that. I tried just doing a standard array first, and I can't even get the autocomplete to show up in the license_number field. I can in different fields, but they are not nested attribute fields.
    – Vesuvious
    Commented Nov 16, 2017 at 17:53

1 Answer 1

0

I have posted a few answers of this very same nature, just in JS and not Rails.

Basically, make you're own search of each object element verses an array.

  source: function(req, resp){
    var results = [];
    $.each(car, function(key, val){
      if(val.license_number.indexOf(req.term) == 0){
        results.push(val);
      }
    });
    resp(results);
  }

Hope that helps.

If you're entering part of a plate, not exactly the start of the number, you can make it more wildcard like: val.license_number.indexOf(req.term) >= 0

Not the answer you're looking for? Browse other questions tagged or ask your own question.