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

4

1 回答 1

2

如果我了解您要做什么,那么您已经很接近了。您只需深入一层即可访问表单构建器正在使用的模型对象:

<td style="width:100px;"><%= nested_f.object.balance_to_date(:dated) %> </td>
于 2013-03-04T23:18:39.080 回答