Tristan Hulbert
Tristan Hulbert

Reputation: 23

Creating Rails objects using same form

I am building an application to manage debts and am trying to create three objects using the same form.

The models are;

  1. Debt (the amount owed)

    class Debt < ActiveRecord::Base
      belongs_to :user
      belongs_to :creditor
      belongs_to :debtor
      accepts_nested_attributes_for :debtor, :creditor
    end
    
  2. Debtor (The person who owes)

    class Debtor < ActiveRecord::Base
      belongs_to :user
      has_many :debts
    end
    
  3. Creditor (The person who is owed)

    class Creditor < ActiveRecord::Base
       belongs_to :user
       has_many :debts
    end
    

I am using the new debt form and would like to show fields for debtor and creditor. So when a new debt is created, so is the associated debtor and creditor.

I have viewed the documentation however, cannot get the fields for debtor or creditor to display on the form.

This is the form

 <%= simple_form_for(@debt) do |f| %>
 <%= f.error_notification %>

 <!-- Debt fields -->
 <div class="form-inputs">
   <%= f.association :user %>
   <%= f.input :amount %>
   <%= f.input :commission %>
   <%= f.input :invoice_issued %>
   <%= f.input :invoice_date %>
   <%= f.input :status %>
   <%= f.input :details %>
</div>

<!-- Debtor Fields -->
 <ul>
  <%= f.fields_for :debtor do |debtor_form| %>
   <li>
    <%= debtor_form.association :user %>
    <%= debtor_form.input :business_name %>
    <%= debtor_form.input :abn %>
    <%= debtor_form.input :first_name %>
    <%= debtor_form.input :last_name %>
    <%= debtor_form.input :email %>
    <%= debtor_form.input :mobile_number %>
    <%= debtor_form.input :phone_number %>
  </li>
 <% end %>
 </ul>

 <div class="form-actions">
  <%= f.button :submit %>
 </div>
 <% end %>

Any help is appreciated.

EDIT

create_table "debts", force: :cascade do |t|
 t.integer  "user_id"
 t.float    "amount"
 t.float    "commission"
 t.boolean  "invoice_issued"
 t.date     "invoice_date"
 t.string   "status"
 t.text     "details"
 t.datetime "created_at",     null: false
 t.datetime "updated_at",     null: false

end

Upvotes: 1

Views: 49

Answers (1)

lei liu
lei liu

Reputation: 2775

You need to build your debt's debtor or creditor in your controller:

#controller
def new
  @debt = Debt.new
  @debt.build_debtor
  @bebt.build_creditor
end

Upvotes: 1

Related Questions