简体   繁体   English

向 collection_select 选项添加按钮

[英]Adding a button to collection_select options

I want to be able to make the first entry in my collection_select a button.我希望能够在我的 collection_select 按钮中创建第一个条目。 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.本质上,如果集合中没有合适的选项,用户应该能够单击下拉列表中的第一个选项,该选项会显示“添加新...”以打开一个用于添加新的模式数据库中填充 collection_select 选项的表的条目。 Is there any way to do this?有没有办法做到这一点?

Two ideas come to mind.有两个想法浮现在脑海。

1. Inject this option as the first with an ID of 0 and catch it in the controller 1.将此选项作为第一个ID为0的选项注入并在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:然后,对于提交表单数据的任何 controller 操作,检查该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 2.触发一些JS或者AJAX

You could have a listener function that triggers when the user selects the 'add new...' option.您可以有一个侦听器 function 当用户选择“添加新...”选项时触发。

This function could open a modal, or redirect to a different page, with a form to add the new thing.这个 function 可以打开一个模式,或重定向到不同的页面,并带有一个添加新事物的表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM