Zulhilmi Zainudin Zulhilmi Zainudin - 4 months ago 22
Ruby Question

How to save JSON array with objects inside Rails JSON column?

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.

Answer

Try this:

var a = <%= @kitchen.special_kitchen_menus.to_json.html_safe %>;
console.log(a);