Unusualslim
Unusualslim

Reputation: 81

What is a better way of collection_select for large datasets?

Currently, I have a model with 100+ records. I have a second model that has_one of the first model. In my form to create the second model, I'm using collection_select calling the first model. The user ends up having to scroll and look through each record. Is there a searchable collection_select or some other form helper that would make this a better experience? Below is my current solution:

  <%= form.collection_select :thing_id, Thing.all, :id, :name, {class: "form-control"} %>

_form.html.erb

<%= form_with(model: order) do |form| %>
  <% if order.errors.any? %>
    <div style="color: red">
      <h2><%= pluralize(order.errors.count, "error") %> prohibited this order from being saved:</h2>

      <ul>
        <% order.errors.each do |error| %>
          <li><%= error.full_message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="form-group">
    <%= form.label 'Status:' %>
    <%= form.collection_select :order_status_id, OrderStatus.all, :id, :status, @order.persisted? ? {class: "form-control"} : {:selected => 1}, {class: "form-control"} %>
  </div>
  <div>
    <%= form.label :subject, style: "display: block" %>
    <%= form.text_field :subject %>
  </div>

  <div>
    <%= form.label :body, style: "display: block" %>
    <%= form.text_area :body %>
  </div>

  <div>
    <%= form.label 'Asset:' , style: "display: block" %>
    <%= form.collection_select :thing_id, Thing.all, :id, :name, {class: "form-control"} %>
  </div>

  <div class="form-group">
    <%= form.label :assigned_to %>
    <%# form.collection_select :assigned_to_id, User.all, :id, :email, {:include_blank => true}, {class: "form-control"} %>
    <%= form.collection_select :assigned_to_id, User.all, :id, :email, {:prompt => true}, {class: "form-control"} %>
  </div>

  <div class="mb-3">
    <%= form.label :images, class: "form-label" %>
    <%= form.file_field :images, {multiple: true, class: "form-control", id: "formFileMultiple", type: "file"} %>
  </div>

  <%= form.hidden_field :requested_by_id, value: current_user.id %>

  <div>
    <%= form.submit %>
  </div>
<% end %>

I'd be happy to include any other code if requested.

Upvotes: 1

Views: 145

Answers (1)

Abdul Basit
Abdul Basit

Reputation: 50

You could use select2 Select2 is a jQuery replacement for dropdown boxes and it contains a searchbox to filter through data and other features too such as lazy loading dropdown options. Check it out https://select2.org/getting-started/basic-usage

Upvotes: 0

Related Questions