我意识到关于如何使用 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/