How to access virtual attributes of model in a nested form with Rails
Asked Answered
K

1

1

I have a basic nested form. I want to access a virtual attribute for the nested form's 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 the 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 the balance to date.

nested_f.balance_to_date(:dated)

Or to be able to do something like

Running the code as shown here gives me:

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

Other than the virtual attribute error, this form works as expected.

The code should produce an editable table of transactions with the balance up to that point. ( [xx] are my way of showing 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 that virtual attribute of the model and the date from the current record being displayed would be really appreciated. I hope I haven't duplicated a previous question.

I'm using Rails 3.2.12 and Ruby 1.9.3.

Thanks! Phil

Kristakristal answered 4/3, 2013 at 19:21 Comment(0)
S
2

If I understand what you're trying to do, you're very close. You just need to drill down one level to access the model object that the form builder is using:

<td style="width:100px;"><%= nested_f.object.balance_to_date(:dated) %> </td>
Slap answered 4/3, 2013 at 23:18 Comment(1)
That was it! Thank you Dan. I forgot all about .object.Kristakristal

© 2022 - 2024 — McMap. All rights reserved.