作为数组一部分的简单表单文本输入字段
Simple form text input fields as part of an array
所以我有 3 个文本输入字段,每个字段代表一个坐标,它们以数组格式 [x, y, z]
存储在我的模型中。
我正在尝试使用输入字段协同工作以生成随表单提交的数组。我目前的代码:
=f.input_field :coordinates[0], value: "1"
=f.input_field :coordinates[1], value: "2"
=f.input_field :coordinates[2], value: "3"
所以我希望我可以在控制器中使用 coordinates
参数将其保存到数据库中。
问题是,使用此设置,产生的 html 是 <input value="1" name="shape[o]" id="shape_o">
而它应该是 <input value="1" name="shape[coordinates][]" id="shape_coordinates_0">
N.B。我的模型中已经有 serialize :coordinates
尝试像这样直接设置自定义属性:
= f.input_field :coordinates, input_html: { value: 1,
id: "shape_coordinates_0",
name: "shape[coordinates][]" }
但我建议在您的模型中为每个坐标创建 attr_readers
,然后将其合并到数组中:
# model:
class Shape < ActiveRecord::Base
attr_reader :x, :y, :z #since you want to serialize it
before_create :build_coordinates
private
def build_coordinates
self.coordinates = [x, y, z]
end
end
在这种情况下,您的视图看起来会很简单:
=f.input_field :x, value: "1"
=f.input_field :y, value: "2"
=f.input_field :z, value: "3"
所以我有 3 个文本输入字段,每个字段代表一个坐标,它们以数组格式 [x, y, z]
存储在我的模型中。
我正在尝试使用输入字段协同工作以生成随表单提交的数组。我目前的代码:
=f.input_field :coordinates[0], value: "1"
=f.input_field :coordinates[1], value: "2"
=f.input_field :coordinates[2], value: "3"
所以我希望我可以在控制器中使用 coordinates
参数将其保存到数据库中。
问题是,使用此设置,产生的 html 是 <input value="1" name="shape[o]" id="shape_o">
而它应该是 <input value="1" name="shape[coordinates][]" id="shape_coordinates_0">
N.B。我的模型中已经有 serialize :coordinates
尝试像这样直接设置自定义属性:
= f.input_field :coordinates, input_html: { value: 1,
id: "shape_coordinates_0",
name: "shape[coordinates][]" }
但我建议在您的模型中为每个坐标创建 attr_readers
,然后将其合并到数组中:
# model:
class Shape < ActiveRecord::Base
attr_reader :x, :y, :z #since you want to serialize it
before_create :build_coordinates
private
def build_coordinates
self.coordinates = [x, y, z]
end
end
在这种情况下,您的视图看起来会很简单:
=f.input_field :x, value: "1"
=f.input_field :y, value: "2"
=f.input_field :z, value: "3"