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

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

I actually have 2 product entries

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 the form. for product 1, the form will contain 2 fields (name and description), and for product 2, the form will contain 3 fields (name, author, creation_data)

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

any help please? Thanks

+6
source share
1 answer

If you use 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 

Remember to specify the parameters in the controller as follows:

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

It is always recommended to use a whitelist of the specific parameters that you need, but if you want to allow everything inside the 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 allow everything for the product model:

 params.require(:product).permit! 

This is not recommended as it will leave your other data outside the json field open for rewriting.

+6
source

Source: https://habr.com/ru/post/984873/


All Articles