I have a couple of virtus objects:
class Calculation
include Virtus.model
include ActiveModel::Validations
include ActiveModel::Model
attribute :age_ranges, Array[AgeRange], default: [{from: 16, to: 22},{from: 24, to: 30}]
end
class AgeRange
include Virtus.model
include ActiveModel::Validations
attribute :from, Integer
attribute :to, Integer
end
And I would like to use form_for
on the new view calculation: I tried this code in the view
<%= form_for(@calculation) do |f| %>
<% @calculation.age_ranges.each do |age_range| %>
<%= f.fields_for :age_ranges, age_range do |age_range_form_builder| %>
<%= age_range_form_builder.text_field :from %>
<%= age_range_form_builder.text_field :to %>
<% end %>
<% end %>
<% end %>
but it doesn't work because the input element is rendered as
<input type="text" value="16" name="calculation[age_ranges][from]">
instead of
<input type="text" value="16" name="calculation[age_ranges[][from]]">
The only way I managed to do it through is the following:
<% @calculation.age_ranges.each do |age_range| %>
<div class="col-sm-6">
<label for="age_from">From</label>
<%= text_field("calculation", "age_ranges[][from]", value: age_range.from) %>
</div>
<div class="col-sm-6">
<label for="age_from">To</label>
<%= text_field("calculation", "age_ranges[][to]", value: age_range.to) %>
</div>
<% end %>
Is there any way to correctly use form_for
here?