ruby-on-railscollection-select

How can I put an "add new" link in a collection_select field in Rails


I want to build a sales_opportunity in my Rails app. The sales_opportunity belongs_to a User and also to a Company. The code works fine as it currently stands, and the form permits a user to select a company to link the sales_opportunity with based on a collection of companies that are pre-defined in the database. What I want is the ability to have a field in the collection_select drop down menu that has "add new company" and takes the user to the companies/new page. At the moment the sales_opportunity cannot be submitted unless a user has previously added companies to his Organization (User belongs_to Organization, Company belongs_to Organization).

The code for the field is as follows:

<div class="form-group">
    <%= f.label :company_id, :class => "col-md-4 control-label" %>
<div class ="col-md-8">
    <%= f.collection_select :company_id, @user.organization.companies(:company_name), :id, :company_name %>
 </div>
</div>

Is there a way I can add a link to this dropdown that will enable the user to add a company to the list if none exists (or if the company he wants to add doesn't exist in the list already)?

The only way I can think to overcome this is for an if statement that has a link to a button to add a company if none exist - but this doesn't cover the scenario where companies are in the database but not the one the user wants.

Any ideas?


Solution

  • You can do this using JavaScript but it will take a bit of work. You question is quite broad so I haven't included any code but I've outlined the basic steps as a starting point.

    1) You'll need to add a JavaScript event handler to watch the dropdown, when the 'add new' option is selected it will trigger an Ajax request.

    2) The Ajax request will render the create action (a modal box would be nice for the user).

    3) When the user submits the form it will update via Ajax.

    4) Reload the dropdown via Ajax to display the new company.

    As you can see, most of the complexity is on the JS side rather than Rails :)