0

Is there a way to submit an array using 'form_for'?

Here's an example of what I mean if I used regular html to pass the values:

<input type="text" name="product[cost][]">

Which should become:

params["product"]["cost"]

But is there any way to do this using form_for?

2 Answers 2

1

Nevermind... I wrote this answer and then realized it is STILL coming through as a string; for some reason rails adds the brackets to the input area but they serve no purpose as far as I can tell. So I agree; best course of action is to use a before_action in the controller and split the string manually. You could get crazy and use simple_form to create a custom input method, but as a newbie I think that gets a little intensive.

I've figured out a way that works. I have my attribute (ingredients) saved to my db as an array, which is important. If the attribute is saved as an array and I use <%= f.text_area :ingredients %>, the text area has a set of square brackets in it. As long as the input is entered inside the brackets, the params receive the input as an array! It's not very pretty, but I'm sure I can fix the display to hide those brackets later on. Hope this helps.

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

Comments

0

No, Rails interprets all form submissions as (escaped) strings. You should convert the string into an array manually on the backend inside a controller action or before_filter.

What is an example of the kind of value you're expecting the user to pass in?

3 Comments

thanks for getting back to me, I'm going to give the user ability to add more fields of the same fields. So I'll have to pass the data in an array for this to work. I might need to just not use form_for. But I like form_for for it's validation abilities to automatically places error divs around the affected fields.
I'm not sure exactly what you're trying to do, but it sounds like you could have the user type in a comma-delimited string like "field1, field2, field3", then split it into an array in the controller and handle remaining business logic from there.
Looks like the form_for does not work with input arrays. I've used form tag which seems to work fine. Thanks.

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.