1

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Hi Lei Liu. After adding @debt.build_debtor in the debts controller, I get the following error 'can't write unknown attribute debtor_id'. Any ideas?
Do you have a debtor_id column in your debt model? please post the schema of your debts table.
Edited to include debts schema
you need to add debtor_id and creditor_id to debts table for your associations

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.