【问题标题】:JSON data type in Rails4 form_forRails4 form_for 中的 JSON 数据类型
【发布时间】:2013-11-05 15:48:38
【问题描述】:

如何实现将 JSON PostgreSQL 类型的值填充到 Rails 中的嵌套形式?

我有一个类似的模型

title :text
description :text
grid :json

我想要存储维度和其他内容的内部属性

{
  "cols": 15, 
  "rows": 15
  "pos": {
      "x": 10, 
      "y": 5
  }
}

对应形式为

@form_for @product do |f|
  f.text_field :title 
  f.text_field :description

  f.fields_for :grid do |grid_f|
     grid_f.text_field :cols 
     grid_f.text_field :rows
  end
end 

但是 cols 和 rows 没有填写。我是否必须手动创建输入并手动设置值。还是因为@product.grid 内部没有符号,而是字符串?

所以@product.grid[:cols] 不起作用,但@product.grid['cols'] 起作用。

【问题讨论】:

    标签: json ruby-on-rails-4 rails-postgresql


    【解决方案1】:

    我相信 formhelper 使用模式生成其字段,并且由于 hstore 中的项目可能会有所不同,因此它无法自动生成这些字段。

    除了实现细节,您可以只迭代对象中的值 (source):

    <% f.grid.attributes.try(:each) do |key, value| %>
      <%= f.text_field key, :input_html => {:value => value } %>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多