jrdioko
jrdioko

Reputation: 33477

Accepting form fields with square brackets in the name in Rails

In a Rails app, I've run into a case where I'd like to have a checkbox name that ends in square brackets, e.g.:

name="foo[bar][baz[]]"

Other special characters seem to be handled correctly, but it looks like Rails is stripping out the square brackets and treating them as declaring an array rather than being part of the name. What needs to be done to allow arbitrary characters (brackets in particular) in this name and have them be processed correctly by Rails?

Upvotes: 1

Views: 1362

Answers (2)

lobati
lobati

Reputation: 10215

If you really need to, you can CGI.escape the values you don't want parsed automatically. You'll then have to CGI.unescape them on the other side.

"foo[bar][#{CGI.escape(name)}]"
CGI.unescape(params[:foo][:bar])

Upvotes: 0

Paulo Fidalgo
Paulo Fidalgo

Reputation: 22296

That's because the square brackets are not allowed in the specification:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

from HTML 4 Basic HTML data types

About the Rails part, and combining these two answers (1 and 2):

Rails make use of square brackets to make associations in the params Hash, so you shouldn't mess with those names.

Upvotes: 1

Related Questions