2016-04-21 33 views
0

所以我有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 PARAM控制器將其保存到數據庫中。 問題是,使用此設置生成的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

嘗試設置自定義屬性直接像這樣:

= 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" 
相關問題