Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails simple_form create form when column type is JSON

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.

like image 942
stytown Avatar asked Mar 01 '15 18:03

stytown


3 Answers

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.

like image 168
IngoAlbers Avatar answered Nov 02 '22 02:11

IngoAlbers


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!

like image 42
Andres Avatar answered Nov 02 '22 01:11

Andres


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])
like image 2
Vlad Hilko Avatar answered Nov 02 '22 01:11

Vlad Hilko