RoR:如何在编辑视图中从数据库设置 collection_select 中的值(1:多关系)

RoR: How to set the value in a collection_select from the database in the edit view (1:many relation)

我目前正在为 1:n 与嵌套表单和集合 select 的关系创建一个复杂的 rails 表单,其中值来自另一个数据 table.

到目前为止,只要用户在更新前没有 select 正确的值,它就会用 collection_select 值列表中的第一个条目覆盖数据库值。我仍然需要正确设置 collection_select 中的初始值。

我已经阅读了很多关于 SO 的问题,最相关的是: f-collection-select-not-displaying-the-selected-value

唯一仍然缺少的(我希望!)是数据库中表单字段值的设置,因此它不会被 select 中的默认值覆盖 select可用值,即使用户没有触及 select.

这段代码源自我的代码和上述问题的解决方案,是错误的。

让一个人拥有很多事物,validthings包含事物的可能值:

在 things table 中只有 Thing 字符串,它们也在 validthings table 中。可以为 collection_select selected 参数提供一个来自事物 table 的字符串,该字符串可以在有效事物 table.[=13= 的值列表中识别出来]

<div class="col-md-12">
  <%= form_for(@person) do |f| %>
    <%= f.fields_for :things do |d| %>
      <%= d.hidden_field :id %><%= d.hidden_field :person_id %>
      <%= d.collection_select(:Thing, Validthings.all, :Thing, :Thing, {:selected => @person.things.map(&:id).Thing.to_s} ) %>
    <% end %>
  <% end %>
</div>

这是错误的地方:

@person.things.map(&:id).Thing.to_s

是的,在 tables persons and things and validthings 中,该列被命名为 "Thing"。它是 table validthings 中的唯一字符串 - 数据库结构不是我的主意,我只使用它。

在这里找到了有用的答案:rails-accessing-current-value-of-a-symbol 转到另一个主题,但我的问题是我不知道如何访问我知道必须已经加载的信息。

这就是我如何将 collection_select 的默认值指定为来自数据库的数据:

<div class="col-md-12">
  <%= form_for(@person) do |f| %>
    <%= f.fields_for :things do |d| %>
      <%= d.hidden_field :id %><%= d.hidden_field :person_id %>
      <%= d.collection_select(:Thing, Validthings.all, :Thing, :Thing, {:selected => d.object.Thing} ) %>
    <% end %>
  <% end %>
</div>

其中 d.object.Thing 是属性 "Thing" 的表单元素的相应对象的值,它已经存在于表单中。

我将非常感谢您提供建设性的想法,以防我的方法与 ruby 不同或类似。我对 ruby、rails 等

比较陌生