为不在模型中的字段创建下拉列表

Create a dropdown for a field not in model

我正在为我视图中的 selecting 城市创建级联下拉列表,因此我需要为 select 州创建第一个,第二个将通过 AJAX.

考虑到我的视图模型中没有 state_id 字段(只有 city_id),我该如何创建第一个字段?

加载编辑视图时,即使没有此值,我如何加载相同的下拉列表和 select 正确的选项?

更新

为了更好地了解我拥有什么和需要什么,这里有一些更多信息。

我有 3 个表:

ID, 姓名, 缩写

城市 ID, 姓名, state_id

患者 ID, 姓名, city_id

想法是在编辑或创建新患者时自动加载状态下拉列表,并且在状态下拉列表中 selected 项目时将加载城市下拉列表。

我试图在我看来使用这段代码:

<div class="row">
        <div class="col-md-4">
          <%= f.input :state, collection: @states %>
        </div>
        <div class="col-md-5">
          <%= f.input :city_id %>
        </div>
      </div>

但是,:state 不存在,因此会导致错误。

您始终可以将其作为一个单独的 select 字段绑定到 jQuery 事件,该事件保存状态数据,如下所示:

#Form

<select id="state_select">
    <option value="IL">Illinois</option>
    <option value="CA">California</option>
</select>

<%= label :city %>
<%= select :city, options_for_select([]) %>

#In Script
$("#state_select").on("change", function(ev) {

    //Set the city based on the state and append it to / overwrite the empty array in cities       

})