Note that there are some explanatory texts on larger screens.

plurals
  1. PORails - Problems refactoring controller's nested attribute creation
    primarykey
    data
    text
    <p>I have models:</p> <pre><code>Transaction has_many :credits, :debits Credit belongs_to :transaction Debit belongs_to :transaction </code></pre> <p>Each credit must have a balancing debit and vice versa.</p> <p>I currently (successfully) achieve this with the following inside Transaction's create method:</p> <pre><code>@transaction = Transaction.new(params[:transaction]) Transaction.transaction do # Balance debits with credits (Sales) if params[:balance_transaction] == 'credit' @transaction.credits.each do |credit| @transaction.debits.push(Debit.new({ :quantity =&gt; 0, :cost_per_unit =&gt; 0, :description =&gt; 'Balancing Debit', :amount =&gt; credit.amount, :account_id =&gt; 23 #Get from settings in future to allow users to choose Debtor account })) end elsif params[:balance_transaction] == 'debit' @transaction.debits.each do |debit| @transaction.credits.push(Credit.new({ :quantity =&gt; 0, :cost_per_unit =&gt; 0, :description =&gt; 'Balancing Credit', :amount =&gt; credit.amount, :account_id =&gt; 43 #Get from settings in future to allow users to choose Creditor account })) end else raise ActiveRecord::Rollback # There's no balancing transaction. Don't save it! end end </code></pre> <p>I tried moving the balancing debit/credit creation into the debit/credit models by replacing <code>@transactions.credits.push(...) with debit.balancing_credit</code> and putting the following in the debit model:</p> <pre><code>def balancing_credit transaction.credits.new({ :quantity =&gt; 0, :cost_per_unit =&gt; 0, :description =&gt; 'Balancing Debit', :amount =&gt; amount, :account_id =&gt; 43 #Get from settings in future to allow users to choose Creditor account }) end </code></pre> <p>I thought this was pretty straightforward refactoring, but it throws up an <code>undefined method 'debits' for nil:NilClass</code> error. Seems it looks in the database for the not yet saved transaction in order to create the balancing credit? Am I doing something wrong?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload