Render fields for array attribute in Rails form object

975 views Asked by At

Right now Im having a hard time to render form fields for the array attribute inside may form object. Im using virtus gem for setting up attributes.

My Code:

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

This is the JournalAccountAttribute Class

class JournalAccountAttribute
  include Virtus.model

  attribute :account, String
  attribute :transaction_type, String
end

The problem is I don't know how to render this in my view. So my relation is 1 Journal has_many accounts.

1

There are 1 answers

0
iskvmk On

According to ActionView - Nested Attributes Examples docs the form in your View should be like:

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