Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails auto complete User object

In my application users belongs to a group and this is done in my Usergroup Model.

class Usergroup < ApplicationRecord
  belongs_to :user
  belongs_to :group
end

class User < ApplicationRecord
  has_many :usergroups
  has_many :groups, through: :usergroups
end

class Group < ApplicationRecord
  has_many :usergroups
  has_many :users, through: :usergroups
end

When I want to add a user to the group though I need to know the ID of the group and the ID of the user which is less than ideal. I created a autocomplete field using jQuery to take care of this for me.

<%= form_with(model: usergroup, local: true) do |form| %>

  <div class="field">
    <%= form.label :user_id %>
    <%= form.text_field :user_id, id: 'user', data: { autocomplete_source: User.order(:email).map(&:email) } %>
  </div>

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

When I attempt to create the new usergroup with the email I selected from this dropdown menu it's submitting because it's requiring there to be a user. How do I pass the complete user object to this field instead of just the email of the user I want to create? Am I approaching this correctly?

This is the route that is being used to get the users.

user GET    /users/:id(.:format)      users#index
like image 835
Trenton Tyler Avatar asked Dec 27 '17 02:12

Trenton Tyler


1 Answers

When I have to find a value from a large list I like to use the gem "select2-rails" gem

you can make an Ajax code to get your values like this

class UserController < ApplicationController
  respond_to :html, :json

  def index
    if params[:email].present?
      @users = User.where(email: params[:email])
    else
      @users = User.all
    end
    respond_with @users
  end
end

in your HTML all you need

<div class="field">
  <%= form.label :user_id %>
  <%= form.hidden_field :user_id, id: 'user_id', class: 'select2' %>
</div>

and in your JS

$(document).ready(function() {
  $('.select2').select2({
    ajax: {
      url: "<%= user_path(format: :json) %>",
      dataType: "json",
      results: function(data, page) {
        return { 
          results: $.map( data, function(user, i) { 
            return { id: user.id, text: user.email } 
          } )
        }
      }
    }
  });
});

I hope that this works for you or points you in the right direction

like image 193
MZaragoza Avatar answered Sep 28 '22 07:09

MZaragoza