在Rails表单对象中渲染数组属性的字段

时间:2017-08-18 05:00:49

标签: ruby-on-rails ruby virtus

现在我很难为内部的数组属性渲染表单字段,这可能会形成对象。我使用virtus gem来设置属性。

我的代码:

class JournalForm
  include Virtus.model

  extend ActiveModel::Naming
  include ActiveModel::Conversion
  include ActiveModel::Validations

  attribute :group_no, String
  attribute :description, String
  attribute :rank_code, String
  attribute :transaction_type, String
  attribute :type, String
  attribute :accounts, Array[JournalAccountAttribute]

  validates_presence_of :group_no, :description, :rank_code, :transaction_type,:type

end

这是JournalAccountAttribute Class

class JournalAccountAttribute
  include Virtus.model

  attribute :account, String
  attribute :transaction_type, String
end

问题是我不知道如何在我看来渲染这个。所以我的关系是1 Journal has_many accounts。

1 个答案:

答案 0 :(得分:0)

根据ActionView - Nested Attributes Examples文档,您的视图中的表单应该是:

<%= form_for @journal do |journal_form| %>
  ...
  <% @journal.journal_accounts.each do |journal_account| %>
    <% if journal_account.active? %>
      <%= journal_form.fields_for :journal_accounts, journal_account do |journal_account_fields| %>
        Account: <%= journal_account_fields.text_field :account %>
        Transaction type: <%= journal_account_fields.text_field :transaction_type %>
      <% end %>
    <% end %>
  <% end %>
  ...
<% end %>