Reputation: 2718
I have an array in my model, containing label IDs:
[ "2", "3", "4", "5", "6", "7", "8", "9", "10", "15", "16", "17", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "40", "50", "89", "90", "96", "97", "98", "100", "102", "103", "104", "106", "107", "109", "111", "112", "113", "114", "115", "116", "117", "118", "119", "120", "121", "122", "123", "124", "18", "125", "126", "127", "128", "129", "130", "131", "135", "136", "140", "201", "202", "203", "252", "253", "301", "302", "303", "304", "352", "354", "358", "359", "401", "402", "403", "404", "405", "407", "408", "451", "452", "453", "454", "457", "501", "503", "504", "551", "552", "553", "554", "555", "556", "557", "601", "602", "603", "604", "605", "606", "607", "651", "652", "655", "656", "657", "658", "701"]
I want the user to be able to edit this array, e.g. removing IDs or add new ones. My simplest thought was to show him the output of the column in a text_area form field and use "as: :array"
<%= f.text_area :labels, :value => @labels, :rows => 11, as: :array %>
That shows the array exactly how it is stored in the database. However, when I edit the form field, the param gets transmitted as:
[ \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\" ....
and it stores an empty array [] in my model. What I want is that what the user is editing in the text area gets also simply stored again as an array. What rails does here is converting my text area value into a string.
I tried to catch the param in my controller and use the eval() method to make it an array again. I also tried the split(",") method but no success.
The database schema has this stored btw:
t.text "labels", array: true
How can I reach my goal?
Upvotes: 1
Views: 1124
Reputation: 4633
Text area helper sends and string containing the content of the input. You need to either parse it before sending the request. Using jQuery normally. Or reparse it into the backend as a valid array.
Eval, as you stated should be working. BUT YOU SHOULD NOT USE IT FOR SECURITY REASONS.
irb(main):004:0> eval("[\"2\"]")
=> ["2"]
In the controller just do:
class FooController < ApplicationController
private
def array_param
eval(param[:array])
end
end
And refer anywhere you need it with: array_param
in the controller methods.
def create
@bar = Bar.new(bar_params.merge({array: array_param}))
#whatever
end
private
def bar_params
params.require(:bar).permit(#everything except the array_param)
end
Upvotes: 3