0

I'm trying to have a dynamic set of inputs in a form, that start with just one, where you can add or remove them with add/delete buttons. Then upon submission of a form, it turns the values of the inputs into a hash then that hash into a string for storing. I really have no idea where to start. So any tips will be helpful.

If using javascript would help, I can go that route, but i'm not sure how to make the javascript and ruby talk.

1
  • 1
    You might want to research nested attributes; Ryan Bates does a railscast on this. You might also be interested in the cocoon gem. Commented Aug 14, 2015 at 22:33

2 Answers 2

2

Depending on your use-case, there are a few options you might want to use. Since you've tagged this with rails, I'm assuming you have access to JQuery. Here's one (very simple) example of how you might go about adding fields to the page dynamically using it:

https://jsfiddle.net/3Lyvw0jm/

If you plan on storing these fields in one of your models, you may want to take a look at implementing nested attributes.

Sign up to request clarification or add additional context in comments.

Comments

1

As pretty much a common web thing (not Rails-specific), you would make the name value look like some_name[].

So instead of having multiple inputs with different names like this:

<input type='text' id='my_input_1' name='my_input_1' value='string_1' />
<input type='text' id='my_input_2' name='my_input_2' value='string_2' />
<input type='text' id='my_input_3' name='my_input_3' value='string_3' />

...where on the server you get:

params :my_input_1 # 'string_1'
params :my_input_2 # 'string_2'
params :my_input_3 # 'string_3'

You would have:

<input type='text' id='my_input_1' name='my_inputs[]' value='string_1'  />
<input type='text' id='my_input_2' name='my_inputs[]' value='string_2'  />
<input type='text' id='my_input_3' name='my_inputs[]' value='string_3'  />

...where on the server you get:

params :my_inputs # ['string_1','string_2',string_3']

2 Comments

What kind of model field do you need for saving this to the database?
This could have a variety of applications, so it would depend on the application. Like, for example, the inputs could be used with a jQueryUI Autocomplete to add tags. The inputs would contain the name of a tag. Then, assuming that your object has a has_many :tags relationship, in the create and update actions you would do something like object_params(:my_inputs).each{|name| @object.tags << Tag.find_by name: name} if object_params(:my_inputs).present?.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.