Rails 4.2+: Mapping PostgreSQL JSONB nested values to form fields -
i have users table settings field of type jsonb (using postgresql 9.5).
i'm trying create form on settings page update user.settings["notifications"][...] values.
class user < activerecord::base end user = user.create(settings: { notifications: { post_created: true } }) user.settings["notifications"]["post_created"] # => true to map nested jsonb values form, however, have this:
# views/form.html.erb <input type="check" name="user[settings][notifications][post_created]" checked="<%= current_user.settings['notifications']['post_created']" %> class settingscontroller def update current_user.settings["notifications"]["post_created"] = params["user"]["settings"]["notifications"]["post_created"] current_user.save end end is there anyway utilize power of rails form builders such can do:
# not work, undefined attribute settings['notifications']['post_created']... <%= form_for current_user, url: settings_path, method: "put" |f| %> <%= f.check_box "settings['notifications']['post_created']" %> <% end %> i understand rails trying map attribute current_user object, , there isn't "attribute" named settings['notifications']['post_created'].
but how 1 go mapping nested jsonb values form field crud activity?
a workable (but not feasible) approach created virtual attributes every single nested value want work with:
class user def settings_notifications_post_created settings["notifications"]["post_created"] end def settings_notifications_post_created=(value) settings["notifications"]["post_created"] = value end end # view... <%= f.check_box :settings_notifications_post_created %> but loses benefit of conventional system since i'm manually typing out every attribute. may write raw html fields , getter/setter methods myself...googling , stack overflow haven't been helpful far, seems there aren't many experience doing kind of stuff yet...
Comments
Post a Comment