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

老子叫甜甜 提交于 2020-01-05 08:10:19

问题


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


回答1:


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>


来源:https://stackoverflow.com/questions/15209362/how-to-access-virtual-attributes-of-model-in-a-nested-form-with-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!