开发者

Submitting an array with form_for

开发者 https://www.devze.com 2023-01-18 08:01 出处:网络
Is there a way t开发者_如何学编程o submit an array using \'form_for\'? Here\'s an example of what I mean if I used regular html to pass the values:

Is there a way t开发者_如何学编程o 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?


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.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消