Rails 3.2 - 多次错误地提交表单

时间:2014-02-03 14:09:17

标签: javascript jquery ruby-on-rails ruby

我有模型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>

以上代码有效,params[:box_videos]提交三个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"}]

在我的控制器中,我只是为数组中的每个哈希创建一个box_video对象,它运行得很好。但是每次我提交嵌套的form_tag表单时都会出现问题,我会向控制器操作发送多个请求!这意味着创建了重复项。

我可以考虑在box_videos控制器创建操作中添加逻辑以检查重复内容,但它似乎相当hacky。谁能告诉我为什么会这样?

1 个答案:

答案 0 :(得分:0)

根据html规范(see this answer),您不能拥有嵌套的表单元素。

您可能希望使用nested forms,它通过jquery和有用的form_helper包装器提供相关模型的创建。

相关问题