【问题标题】:Storing and Retrieving postgres nested JSONB data type in rails form以rails形式存储和检索postgres嵌套的JSONB数据类型
【发布时间】:2016-05-21 11:35:54
【问题描述】:

我意识到没有太多关于如何使用 rails 表单来存储和检索 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'] 可能是 nil,当我调用 @car.locations['primary_location']['district'] 时会出现错误。

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

谢谢

【问题讨论】:

    标签: ruby-on-rails json forms postgresql jsonb


    【解决方案1】:

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

    使用.try() 方法。

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

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

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

    【讨论】:

    • 嗨,你会如何使用 store 来实现它?它如何将数据检索到表单中?
    • 表单只是简单地调用你的字段的访问器,所以只需添加相应的store_accessors。至于级别超过 1 的 json,我会在视图中编写循环。
    • 谢谢。你能写一个例子来帮助我更好地理解吗?谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 2015-06-06
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 2023-03-05
    • 2019-11-18
    相关资源
    最近更新 更多