Search code examples
ruby-on-railsformsbelongs-to

Ruby on Rails - Forms with belongs_to association


On Rails 4. I have three Models (for this question): Users, Organizations, and UserOrganizations. Users can have many organizations, and organizations can have many users. This relationship is stored in UserOrganizations with user_id and organization_id. So, UserOrganizations belongs to users and organizations.

When I want to add a new user/organization relationship, the user_id is automatically taken from the current user logged in. However, to assign that user to an organization, I have a dropdown select, listing all the organizations in the database (by name).

This is fine in the dev environment but not so great when I will eventually have over a thousand organizations.

What I would like to do is have a sort of text look-up input where the user can type in an organization's name and then all orgs in the database containing that name will display. Then the user can select the name (through a radio button maybe?) to tell the app which org he/she would like to be assigned. Ideally, this would happen on the same page/no reload.

What is the best way to create this form? Is there a gem or something else that exists to easily make this? Can you do this with formtastic or even without a gem? Thank you for any help.


Solution

  • You should probably take a look to rails3-jquery-autocomplete gem. It has quite documentation and examples. More or less:

    Model:

    class UserOrganization < ActiveRecord::Base
      attr_accessor :organization_name
    end
    

    Controller:

    class UserOrganizationsController < Admin::BaseController
      autocomplete :organization, :name
    end
    

    Routes:

    resources :user_organizations do
      get :autocomplete_organization_name, :on => :collection
    end
    

    View:

    form_for(@user_organization) do |f|
      f.hidden_field :organization_id, id: 'org_id'
      f.autocomplete_field :organization_name, autocomplete_organization_name_user_organizations_path, id_element: '#org_id'
    end
    

    It also provides integration with SimpleForm and Formtastic.