0

So I have 3 text input fields and each one represents a co-ordinate and they are stored in the array format [x, y, z] in my model.

I am trying to use the input fields to work together to produce an array submitted with the form. My code currently:

=f.input_field :coordinates[0], value: "1"
=f.input_field :coordinates[1], value: "2"
=f.input_field :coordinates[2], value: "3"

So my hoping is that I can use the coordinates param in the controller to save it to the database. The issue is that with this setup the html produced is <input value="1" name="shape[o]" id="shape_o"> when it should be <input value="1" name="shape[coordinates][]" id="shape_coordinates_0">

N.B. I already have serialize :coordinates in the model

1 Answer 1

1

Try to set your custom attributes directly like this:

= f.input_field :coordinates, input_html: { value: 1,
                                            id: "shape_coordinates_0", 
                                            name: "shape[coordinates][]" }

But I suggest to create attr_readers in your model for each coordinate and then unite it in array:

# 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

In this case your view will look much easy like:

=f.input_field :x, value: "1"
=f.input_field :y, value: "2"
=f.input_field :z, value: "3"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.