Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  end
end 

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.

like image 685
Douglish Avatar asked Nov 11 '22 19:11

Douglish


1 Answers

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 %>
like image 159
Rescribet Avatar answered Nov 15 '22 12:11

Rescribet