Reputation: 9345
I have a Kitchen model and I want to add menu list called special_kitchen_menus
into it.
I can update the kitchen. But, I get this when I console.log()
the result from database:
[{"name"=>"pizza", "price"=>29}, {"name"=>"burger", "price"=>24}, {"name"=>"cake", "price"=>39}]
Line of code that do the console.log()
var a = "<%= @kitchen.special_kitchen_menus %>";
console.log(a);
I try to use serialize
and create my own method called convert_to_hash
. But I got no luck at all.
schema.rb
create_table "kitchens", force: :cascade do |t|
# other columns
t.json "special_kitchen_menus", default: {}
end
kitchen model
class Kitchen < ActiveRecord::Base
# serialize :special_kitchen_menus
# def convert_to_hash
# self.special_kitchen_menus = self.special_kitchen_menus.to_h
# end
end
kitchen controller
# before_action :convert_to_hash, only: [:update]
def update
@kitchen = Kitchen.find(params[:id])
if @kitchen.update(kitchen_params)
redirect_to @kitchen
else
render :edit
end
end
def kitchen_params
params.require(:kitchen).permit(:special_kitchen_menus)
end
form
<%= form_for @kitchen do |f| %>
<!-- other fields -->
<label>Special Kitchen Menus</label>
<%= f.text_field :special_kitchen_menus %>
<%= f.submit "Update" %>
<% end %>
sample data for update
[
{ "name": "pizza", "price": 29 },
{ "name": "burger", "price": 24 },
{ "name": "cake", "price": 39 }
]
What should I do to update the input data correctly so that I can retrieve it back correctly just the input data without that weird characters?
Note 1: I don't want to store the data in another model OR use nested attribute. I just want to store the data inside this Kitchen model using the same Kitchen's form.
Note 2: I'm using postgres database. Not sqlite for this app.
Upvotes: 2
Views: 5930
Reputation: 34318
I don't think you can save JSON array in JSON type column. In the JSON type column, you can only store VALID JSON object. As, array of JSON is not a JSON object, so you should not be able to store that in a json column in Rails. Postgres has an array column type. You should use that to store array of JSON objects instead.
You can use jsonb column type to store array of JSON objects in the database. Take a look at this stackoverflow answer pointed by @brg in the comment section.
Upvotes: 2
Reputation: 3985
Try this:
var a = <%= @kitchen.special_kitchen_menus.to_json.html_safe %>;
console.log(a);
Upvotes: 2