Adding a button to collection_select options

33 views Asked by At

I want to be able to make the first entry in my collection_select a button. In essence, if a suitable option is not available in the collection, the user should be able to click on the first option in the dropdown that will say 'add new...' to open a modal that will be used to add a new entry to the table in the database that is populating the collection_select options. Is there any way to do this?

1

There are 1 answers

0
Chiperific On

Two ideas come to mind.

1. Inject this option as the first with an ID of 0 and catch it in the controller

# in the controller
@select_options = ['add new...', 0]
@select_options << Book.all.pluck(:name, :id)

# form field
<%= select_tag('book',  @select_options.flatten, { include_blank: false }) %>

Then, to whatever controller action the form data gets submitted, check for that 0 ID:

if params[:book].zero?
  # user selected 'add new...'
  redirect_to create_book_path 
else
  # do the normal thing
end

2. Trigger some JS or AJAX

You could have a listener function that triggers when the user selects the 'add new...' option.

This function could open a modal, or redirect to a different page, with a form to add the new thing.