How to access virtual attributes of a model in a nested form using Rails

I have a basic nested form. I want to access a virtual attribute for a nested form model.

Model 1: Lease
  Has_many :transactions
  accepts_nested_attributes_for :transactions, :reject_if => lambda { |a| a[:dated].blank? }, :allow_destroy => true
  ...

Model 2: Transaction
  belongs_to :lease
  def balance_to_date(aDate)
    #Returns the current balance up to aDate
    ...
  end
  ...

In a nested form, I want to put something like:

<td style="width:100px;"><%= nested_f.text_field :dated, size: 8 %> </td>
<td style="width:100px;"><%= nested_f.text_field :label, size: 8 %> </td>
<td style="width:100px;"><%= nested_f.text_field :credit, size: 6  %> </td>
<td style="width:100px;"><%= nested_f.text_field :debit, size: 6  %> </td>
<td style="width:100px;"><%= nested_f.balance_to_date(:dated) %> </td>

And I want the following to give me balance today.

nested_f.balance_to_date (: dated)

Or to do something like

Executing the code as shown here gives me:

undefined method `balance_to_date' for#<ActionView::Helpers::FormBuilder:0xac78bac>

In addition to the virtual attribute error, this form works as expected.

An editable transaction table with the balance to this point should appear in the code. ([xx] is my way of displaying input fields).

   Dated         Label      Credit    Debit   Balance  
 [ 1/1/2012 ]  [ Rent due ] [       ] [ 600 ]  -600  
 [ 1/2/2012 ]  [ Payment  ] [ 600   ] [     ]  0 
 [ 2/1/2012 ]  [ Rent due ] [       ] [ 600 ]  -600 
 [ 2/2/2012 ]  [ Payment  ] [ 500   ] [     ]  -100 
 [ 3/1/2012 ]  [ Rent due ] [       ] [ 600 ]  -700 
 [ 3/6/2012 ]  [ late fee ] [       ] [ 50  ]  -750 
 [ 3/7/2012 ]  [ Payment  ] [ 800   ] [     ]  50 
 [ 4/1/2012 ]  [ Rent due ] [       ] [ 600 ]  -550

Any advice on how to access and display this virtual model attribute and date from the currently displayed record will be really appreciated. I hope I did not repeat the previous question.

Rails 3.2.12 Ruby 1.9.3.

!

+1
1

, , . , :

<td style="width:100px;"><%= nested_f.object.balance_to_date(:dated) %> </td>
+1

Source: https://habr.com/ru/post/1666311/


All Articles