简体   繁体   中英

How rails do nested form in one form?

The scenario is that, I want to design a Post form which is used to record what fruit I eat in one meal, include picture , content , many kind of fruit . The model relationship is that,

Post has_many fruits
Fruit belong_to post

I usee Jquery-ui to make autocomplete in order to help user type their fruit. After they type there fruit tag, it will create a tag under the input field. Like this

在此处输入图片说明

However how to I create this in form? I thought about dynamic nested form, but I don't want there're a lots of form, I wish there would be only one input and do the same thing with dynamic nested form.

Here is the github , please let me know if I need to provide more information.

 $(document).on('click','#add_fruit',function(e){ e.preventDefault(); addFruitTag(); }); function addFruitTag(){ var content = $('#content').val().trim(); var fruit = $('#fruit').val().trim(); if(content.length <1 || fruit.length < 1){ alert("Please fill content and fruit"); }else{ $('#fruit_tags').append( $('<input>') .attr('type','checkbox') .attr('name','fruits[]') .attr('value',$('#fruit').val()) .prop('checked','true') ) .append( $('<label>') .text($('#fruit').val()) ) .append($('<br>')); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="#" method="GET"> Content : <input type="text" id="content" name="content"><br/> Fruit : <input type="text" id="fruit"> <button id="add_fruit">Add Fruit</button><br/> <div id="fruit_tags"> </div> <input type="submit" value="Create Post"> </form> 

Note: I don't have much idea about auto complete plugin, so I have created the function addFruitTag() , call it where you are calling your function of adding hash tags of fruits.

And when you will submit the form to the server, you can retrieve the added fruits by accessing the fruits[] variable , which will be an array containing the selected fruits tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM