【发布时间】: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