0. Essentials
Using a Rails form and inputs, how do you concatenate a large number of text inputs into one string attribute?
e.g. "A" , "B", "C" are each inputs in a Rails form and they are to be concatenated and read in as :string_field => "ABC"
1. Background
I'm making an application that allows user to make their own crossword puzzles. The puzzles are members of my CrosswordPuzzle class, in which the :letters
attribute (a string) describes the layout of letters and black spaces in the puzzle.
For example, a 3x3 puzzle as follows...
FOO
O■U
BAR
... should have a :letters
attribute of "FOOO_UBAR"
(the string represents the puzzle read left to right, top to bottom).
2. Problem
Users create a puzzle by first specifying a size for the puzzle (row x col). This creates a blank puzzle of that size, with each cell being a blank HTML input element. Users can then type the appropriate letters into the blank cells and construct their puzzle.
What I don't understand how to do is take all of these separate single-character inputs and have Rails interpret them or change them into a single :letters
attribute of the puzzle when I submit the edit form. Also, because the puzzles may be of varying sizes with varying numbers of cells, the answer needs to be scalable such that 100-600 input elements can be read into the single 100-600 character string.
Any help would be much appreciated.
P.S. As this is my first post on StackOverflow I apologize in advance if I've made any mistakes. (I checked extensively before to see if similar topics had been covered, but they either haven't or I'm too unfamiliar with the terminology to recognize them)
Configure your form so that each text input has a name like cell[?]
where the ? is a zero based array index. So, cell[0]
, cell[1]
, etc. Rails will turn all of those into a single parameter entry cell
which will be an array. Then, just join them together.
Skipping rails... something like this.
1.8.7 > a = []
=> []
1.8.7 > a[0] = 'f'
=> "f"
1.8.7 > a[1] = 'o'
=> "o"
1.8.7 > a[2] = 'o'
=> "o"
1.8.7 > a[3] = 'o'
=> "o"
1.8.7 > a
=> ["f", "o", "o", "o"]
1.8.7 > a.join
=> "fooo"
1.8.7 >
Or.. do the same thing, but on the client side using javascript, stuffing the result into a hidden 'letters' field and then Rails doesn't have to do anything.