Rails simple_form create form when column type is JSON
Asked Answered
C

4

7

I have a model (FooBar) with three columns:

Foo -> String
Bar -> JSON
Baz -> String

I want to create a form for this model

Bar has default attributes of: {zing: {}, zaz: {}, laz: {}}

I would like to have the following inputs:

f.input :foo
f.input :zing
f.input :zaz
f.input :laz
f.input :baz

I tried to do this using fields_for and passing in each key and converting it to a symbol:

bar.each do |k,v|
f.input k.to_sym
end

but the error I'm getting is that FooBar has undefined method of :zaz

Any ideas would be appreciated, thanks.

Canady answered 1/3, 2015 at 18:54 Comment(0)
S
3

You should be able to do it like this:

f.simple_fields_for :bar do |bar_f|
  bar.each do |k,v|
   bar_f.input k.to_sym
  end
end

Don't forget to allow the parameters in the controller.

Stgermain answered 9/4, 2015 at 8:46 Comment(0)
B
3

You can do something like this:

class User < ActiveRecord::Base
  serialize :preferences, HashSerializer
  store_accessor :preferences, :blog, :github, :twitter
end

And then you will have access to blog, github and twitter just as if they were normal properties in the model and your form is going to look something like this:

= simple_form_for(@user, html: { class: "form" }) do |f|
  = f.input :blog
  = f.input :github
  = f.input :twitter

You have more info in this link! https://github.com/plataformatec/simple_form/wiki/Nested-inputs-for-key-value-hash-attributes

Hope it helps!

Brunelle answered 14/2, 2017 at 12:36 Comment(0)
B
2

Set @temp variable

@temp = FooBar.new
@temp.data = {zing: "", zaz: "", laz: ""}

This code works for me

<%= simple_form_for @temp do |f| %>
  <%= f.simple_fields_for :data do |data_f| %>
    <% @temp.data.each do |k,v| %>
      <%= data_f.input k.to_sym %>
    <% end %>
  <% end %>
  <%= f.button :submit %>
<% end %>

Don't forget about permission params

params.require(:temp).permit(data: [:zing, :zaz, :laz])
Birgitbirgitta answered 30/5, 2017 at 21:26 Comment(1)
How to show the input box with value. It does not populate the input box with the valueLatonia
P
2

If you don't want to define accessors, you could do something like:

= simple_form_for(@foo_bar) do |f|
  = f.simple_fields_for :bar do |bf|
    = bf.input :zing, input_html: { value: f.object.bar[:zing] }
    = bf.input :zaz, input_html: { value: f.object.bar[:zaz] }
    = bf.input :laz, input_html: { value: f.object.bar[:laz] }

You would need to initialise bar with {} in your controller

Pola answered 4/1, 2022 at 14:14 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.