Get and set json type data on html form in Rails

(1) In MySQL 5.7 a native "JSON" data type is added. You can utilise the this data type to save some no-relational, dumb data.

(2) For example, you have a products table and you needs to save the dimensions of the product. You can do it this way:

create_table :products do |t|
  ...
  t.json :dimensions
  ...
end

Then, save dimensions as:

{
  "h": "100"
  "w": "50"
  "l": "75"
}

(3) To inputs these data on html form, you need the form similar to a nested type. Except that you need to render each field via a loop and print the value via the "value" attribute.

<%= form_for @product, url: {action: 'create'}, method: 'post', html: {class: 'form'} do |f| %>
  ...
  ...
  <%= f.fields_for :dimensions do |fields| %>
    <% @product.dimensions.each do |k, v| %>
      <div>
        <%= fields.label(k.to_sym, k.humanize) %>
        <%= fields.text_field k.to_sym, maxlength: '5', value: v %>
      </div>
    <% end %>
  <% end %>
  ...
  ...
<% end %>

(4) You will also need to permit these fields in your controller.

params.require(:product).permit(..., dimensions: %i[l w h])

(5) With this you can now get and set JSON fields on html form.


AI Summary
Chrome On-device AI 2024-10-04 22:31:11

Share Article