How to work with rails form and jsonb postgres
I don't know about the previous versions but in Rails 6 from the doc: https://api.rubyonrails.org/classes/ActiveRecord/Store.html
you can use store like this:
class MyModel < ApplicationRecord
store :my_jsonb_field_name, accessors: [:property1, :property2]
end
Now if you have a form with <%= form.text_field :property1 %>
and <%= form.text_field :property2 %>
they will be automatically mapped to your json/jsonb field and you will be able to treat them like if they were a regular (varchar/string) fields.
Do Not forget to permit :property1 and property2 etc in your strong parameters, i.e:
params.require(:my_model).permit(:title, [...], :property1, :property2)
Use store_accessors
. Form data is just a Hash
, that could be easily converted to a JSON
object and persisted in postgresql without major problems.
Assuming your form submits all profile data in a profile[]
hash and your models look something like this:
class User < ActiveRecord::Base
has_one :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
store_accessor :profile
end
You could simply do something like:
user.profile = params[:profile]
user.profile.save
In your controller (or anywhere else) and it should work.