简单表单文本输入字段作为数组

时间:2016-04-21 19:32:00

标签: ruby-on-rails arrays simple-form

所以我有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

1 个答案:

答案 0 :(得分:1)

尝试直接设置自定义属性:

= 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"
相关问题