Douglish Douglish - 1 year ago 69
JSON Question

JSON data type in Rails4 form_for

how to achieve filling values from JSON PostgreSQL type into nested form in rails?

I have a model like

title :text
description :text
grid :json

Inside properties I want to store a dimension and other stuff

"cols": 15,
"rows": 15
"pos": {
"x": 10,
"y": 5

Corresponding form as

@form_for @product do |f|
f.text_field :title
f.text_field :description

f.fields_for :grid do |grid_f|
grid_f.text_field :cols
grid_f.text_field :rows

But cols and rows are not filled in. Do I have to manually create the input and set value manually. Or is it because inside the @product.grid are no symbols, but strings?

So @product.grid[:cols] doesn't work, but @product.grid['cols'] does.

Answer Source

I believe that formhelper generates its fields with use of the schema and since the items in a hstore can vary, it can't generate those fields automatically.

Apart from the implementation details, you can just iterate over the values in your object (source):

<% f.grid.attributes.try(:each) do |key, value| %>
  <%= f.text_field key, :input_html => {:value => value } %>
<% end %>