保存在Rails中DB js生成的字段中

Save in DB js-generated field in Rails

本文关键字:字段 DB 存在 Rails 保存 js      更新时间:2023-09-26

我在Rails中有一个表单,非常基本。但我决定添加一些功能。一点背景。
你选择你是男性还是女性,然后表单生成一些字段。我有一个已经存在于V1的字段,但是当我用javascript生成它时,它没有保存在DB中。我真的不明白为什么。下面是一些代码:

<标题>控制器h1> 视图

原始字段

<%= f.select "size", options_for_select(size, @pokemon.size) %>

size是哈希值

创建了一个,但不成功

var s = document.createElement("select");
s.name = "po";
s.id = "pokemon_size";
sex.appendChild(s);
for(i in size) {
  document.formName.po.options[i] = new Option(size[i], size[i]);
}

我认为这是因为我的新元素的名称不是pokemon[size],但当我使用它时,行document.formName.pokemon[size]。选项[i]不再工作了。

所以我有点挣扎,看看我怎么能使这个工作。谢谢!

假设从你的控制器代码中,你的表单字段的命名空间为"pokefuck",那么你需要让你的选择名称为"pokefuck[size]",然后在表单的元素集合中引用该名称:

var s = document.createElement("select");
s.name = "pokefuck[size]";
s.id = "pokemon_size";
sex.appendChild(s);
for(i in size) {
  document.formName.elements['pokefuck[size]'].options[i] = new Option(size[i], size[i]);
}

字段的名称需要将其放入您的pokefuck的params散列中。

pokefuck[size]应该是表单元素的名称。将表单元素附加到要提交的表单元素。