我有模型Box,每个Box有很多box_videos(另一个模型)。我希望用户能够将 box_videos 添加到框中,因此我为此创建了以下编辑表单(在创建 @box 之后):
<%= form_tag "/box_videos", { method: :post, id: "new_box_videos", remote: true } do %>
<%= text_field_tag "box_videos[][link]", '' %>
<%= text_area_tag "box_videos[][description]", '' %>
<%= hidden_field_tag("box_videos[][box_id]", @box.id) %>
<%= hidden_field_tag("box_videos[][user_id]", current_user.id) %>
<div class="another_video">Add Another Video</div>
<%= submit_tag "Save Videos" %>
<% end %>
<%= form_for(@box) do |f| %>
<%= f.text_field :name %>
<%= f.text_field :size %>
<%= f.text_field :all_other_attributes %>
<%= f.submit "Create Box" %>
<% end %>
以及一些 Javascript,以便于一键添加更多 box_videos。
<script>
$('.another_video').click(function() {
$('#new_box_videos').prepend('<input id="box_videos_link" name="box_videos[][link]" placeholder="Link to a youtube video." style="width: 18em;" type="text" value=""><textarea id="box_videos_description" name="box_videos[][description]" placeholder="Describe this video." style="width: 18em;"></textarea><br/><br/><input id="box_videos_box_id" name="box_videos[][box_id]" type="hidden" value="' + gon.box_id.toString() + '"><input id="box_videos_user_id" name="box_videos[][user_id]" type="hidden" value="' + gon.user_id.toString() + '">');
});
</script>
上面的代码是有效的,提交三个box_videos时的params[:box_videos]
如下:
[{"link"=>"https://www.youtube.com/watch?feature=player_detailpage&v=dpAP8bq3ddU
", "description"=>"foo", "box_id"=>"63", "user_id"=>"16"}, {"link"=>"https
://www.youtube.com/watch?feature=player_detailpage&v=dpAP8bq3ddU", "description"
=>"bar", "box_id"=>"63", "user_id"=>"16"}, {"link"=>"https://www.you
tube.com/watch?feature=player_detailpage&v=dpAP8bq3ddU", "description"=>"hello world",
"box_id"=>"63", "user_id"=>"16"}]
在我的 Controller 中,我只需为数组中的每个哈希创建一个 box_video 对象,效果就很好。但是当我每次提交嵌套的 form_tag 表单时,问题就出现了,我向 Controller 操作发送多个请求!这意味着正在创建重复项。
我可以考虑向 box_videos Controller 创建操作添加逻辑来检查重复的内容,但这看起来相当老套。谁能告诉我为什么会发生这种情况?
最佳答案
根据 html 规范 ( see this answer ),您不能嵌套表单元素。
您可能想使用nested forms为此,它提供了通过 jquery 和有用的 form_helper 包装器创建关联模型的功能。
关于javascript - Rails 3.2 - 表单多次错误提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21529486/