ruby-on-rails - 以 rails 形式存储和检索 postgres 嵌套的 JSONB 数据类型

标签 ruby-on-rails json forms postgresql jsonb

我意识到关于如何使用 rails form 存储和检索 JSON 类型数据的信息并不多。我目前面临以下问题:

我有一个在 JSON 中创建嵌套结构的表单:

= form_for(@car) do |cf|
    = cf.fields_for :locations do | locations_f |
        = locations_f.fields_for :primary_location do | primary_location_f |
            .sm-col.md-col.sm-col-6.px2
                label.inline-block.mb1 District
                = primary_location_f.text_field :district 
            .sm-col.md-col.sm-col-6.px2
                label.inline-block.mb1 Street
                = primary_location_f.text_field :street 

它将生成输入 HTML 标签:

<input name="car[locations][primary_location][district]">

<input name="car[locations][primary_location][street]">

在执行 params.permit 后,我能够将其保存在数据库中:

params.require(:car).permit([
    locations:[primary_location:[:street, :district]]
])

我还创建了 store_accessor在模型中

store_accessor :locations, :primary_location, :other_locations

但是,在我持久化数据之后,我希望它显示在 text_field 中数据库中已经存在的内容。我尝试做类似的事情:

= primary_location_f.text_field :district, value: @car.locations['primary_location']['district']

但是,它有时会遇到 NilClass 错误 @car.locations['primary_location']可能为零,当我调用 @car.locations['primary_location']['district'] 时会出现错误.

我想知道存储和检索 JSON 数据类型的最佳方式是什么。当 JSON 嵌套时,什么是好方法。

谢谢

最佳答案

However, it will run into NilClass Error as sometimes @car.locations['primary_location'] may be nil, and error will arise when I call @car.locations['primary_location']['district'].

使用.try()方法。

@car.locations.try(:[],:primary_location).try(:[], :district)

I wonder what is the best way to store and retrieve JSON data type. And what is a good way when the JSON is nested.

我更喜欢内置 JSON store。与您正在使用的类似。

关于ruby-on-rails - 以 rails 形式存储和检索 postgres 嵌套的 JSONB 数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37362387/

相关文章:

javascript - 使用 Javascript 或 jQuery 获取表单输入以进行背景颜色操作

Javascript 验证 : Return false not working, 表单仍在提交

ruby-on-rails - Carrierwave:在第二个模型中复制文件

ruby-on-rails - OmniAuth 单点登录与设计,invalid_credentials

javascript - 创建以变量名作为键的 Javascript 对象

javax.json : Build a JSONArray from a List<Integer> and add it to a JSONObject

json - 在 MVC 3 中捕获正确 JSON 格式的错误时,如何使用 ELMAH 记录错误

java - 通过 Stripes 将 POST 数据映射到对象

ruby-on-rails - 检查 create rails 上的记录是否成功创建

ruby-on-rails - 如何检查字符串的最后一个字母?