如何使用rails对象的id在选择下拉列表中设置选项的值

我在Rails中有一个模态,用于构建公司对象,将其返回到我的选择下拉列表(具有正确的名称),预先设置并自动选择它。 但是,数据库中的现有对象在列表中显示为rails生成的选项,并且同时包含选项的名称和值 – 该值是它们的object.id,因此我可以将两个模型关联在一起。 我不能为我的生活找出如何编写javascript来更新下拉列表中的值以及它的文本。

我目前的jquery:

//close the modal $('#competitor_modal').modal('hide'); //prepend the name of the company to the select dropdown $('#sales_opportunity_company_id').prepend($('', { text: , })); //select the newly prepended option $('#sales_opportunity_company_id>option:eq(0)').attr('selected', true); //show the submit button (I hide it whilst they are creating a new company to stop them accidentally submitting with the value "add new company" $('#submit').show(); 

我试过用过:

  

要检索ID,但这不起作用。 我也尝试了所有有人试图获得自动设置的值(例如只是尝试将整个rails对象添加到表单中),没有运气。

我当前代码生成的html:

  2 Any company Add new company  

如您所见,我没有正确的ID传递。 我究竟做错了什么?

试试这个:

 // remove previously selected value: $("#sales_opportunity_company_id :selected").removeAttr("selected"); // add new option as selected value: $("#sales_opportunity_company_id").prepend('');