I have a Settings table with 5 boolean fields. I want to be able to create and update those fields via JSON. From what I understand, Rails converts all parameters to strings, so that boolean values always return true. If I send:
{ "settings": { "setting1":true, "setting2":false } }
And then try doing: Setting.new(params[:settings]), both settings will be true in the database, since the second setting’s value of false is translated to "false", and thus actually evaluates to true. Actually I can’t even do that, as I get:
NoMethodError (undefined method `stringify_keys' for #<String:0x000000213dcbd0>)
on that line. Some suggestions from the internet say to compare the parameters against "true", and then store that. This is a huge pain though, because then I can’t take advantage of mass-assignment. I don’t want to have to do this:
@setting = Setting.new
@setting.setting1 = (params[:settings][:setting1].eql? "true")
...
For all 5 fields, especially since I will have to do that for create, update, and even from other controllers (some controllers accept JSON to create a settings object along with their own attributes).
Is there a better way to go about this? JSON APIs seem pretty standard with Rails, it seems like this would be taken care of in a more elegant way?
How about just making a convertor class and sticking it in a before filter?
It is probably more consistent with Rails to assign the changed params to a new Hash object and to pass that to the model.