Rails中的fields_for和PORO(Virtus)

时间:2019-02-07 14:22:27

标签: ruby-on-rails ruby forms virtus

我有几个虚拟物体:

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

我想在新的视图计算中使用form_for:我在视图中尝试了这段代码

<%= 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 %>

但是它不起作用,因为输入元素呈现为

<input type="text" value="16" name="calculation[age_ranges][from]">

代替

<input type="text" value="16" name="calculation[age_ranges[][from]]">

我设法做到这一点的唯一方法是:

<% @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 %>

这里有没有办法正确使用form_for

0 个答案:

没有答案