I am trying to save a JSON file into a database. The JSON file is dynamically created. Hence, the number of values in the JSON change with time.
The JSON generated and passed to the controller is(Here two objects were dynamically created for the JSON) -
{"row_values"=>{"0"=>{"name" => "abc", "age" => "12"}, "1"=>{"name" => "xyz", "age" => "21"}}}
The ajax query made is -
$.ajax({
data: JSON_main_data,
url: '/daily_work_updates',
type: "POST"
success: function(data){
if (data ==true)
alert("Data saved successfully");
else
alert("Data not saved successfully");
,
dataType: 'JSON'
});
The function in my controller used to save the data to the database -
def create
params[:row_values].each do |data|
saved = DailyWorkUpdate.create(data)
end
respond_to do |format|
format.html{ redirect_to new_daily_work_update}
format.js
format.json{ render json: saved }
end
end
I have used the strong parameters-
def daily_work_update_params
params.require(:row_values).permit( row_values: [:name, :age] )
end
This does not work as create expects a hash value. How can I successfully save all the data dynamically generated by the JSON to my database?
I have come across many similar questions but none helped me. I am new to rails. It would help a ton! I am using rails version 4
Aucun commentaire:
Enregistrer un commentaire