0

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?

rickyz
  • 71
  • 7
  • 1
    Welcome to Stack Overflow. What have you tried? Do you have an code written? – Beartech Jul 30 '22 at 02:55
  • I'm rather new to Ruby on Rails and I did some research on this, but I wasn't able to find much. I know that I can customize the class of the input and I know that I can add functions that will effect all options under the collection, but I couldn't find anything for customizing a single option. Assuming that it works, I am leaning towards writing the collection_select code in html rather than using the Ruby tags. – rickyz Aug 01 '22 at 13:40

1 Answers1

0

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.

Chiperific
  • 4,428
  • 3
  • 21
  • 41