Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to show a form with fields for the jsonb properties

I have a Product model with a jsonb field called dynamic.

I have actually 2 product records

Product 1 :

dynamic = {"name": "super product 1", "description": "lorem ipsum text" }

Product 2 :

dynamic = {"title": "this is an ebook", "author": "john doe", "creation_date": "2015"}

To edit each product I need to show a form. for the product 1 the form will contains 2 fields (name and description), and for product 2 the form will contains 3 fields (title, author,creation_date)

I have searched but it seem that all the articles I have found talk about how to use the console to save or edit a json field but no one talks about how to use the form.

any help please ? Thanks

like image 902
medBouzid Avatar asked Apr 08 '15 22:04

medBouzid


1 Answers

If you are using simple_form you can do something like this:

f.simple_fields_for :dynamic do |dynamic_f|
  @product.dynamic.each do |k,v|
    dynamic_f.input k.to_sym
  end
end

Don't forget to allow the parameters in the controller like this:

params.require(:product).permit(dynamic: [:name, :description, :title, :author, :creation_date]])

It is always good practice to whitelist the specific params that you need but if you want to allow everything inside dynamic you can try something like this:

params.require(:product)permit( **permitted paramters in here** ).tap do |whitelisted|
  whitelisted[:dynamic] = params[:product][:dynamic] if params[:product][:dynamic]
end

Or to allow everything for the product model use:

params.require(:product).permit!

This is not recommended though as it would leave your other data outside of the json field open to be overwritten.

like image 136
IngoAlbers Avatar answered Oct 13 '22 00:10

IngoAlbers