如何使用Rails以嵌套形式访问模型的虚拟属性 [英] How to access virtual attributes of model in a nested form with Rails

查看:99
本文介绍了如何使用Rails以嵌套形式访问模型的虚拟属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的嵌套表单.我想访问嵌套表单模型的虚拟属性.

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)

nested_f.balance_to_date(:dated)

或者能够做类似的事情

运行如下所示的代码可以给我:

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.

代码应生成一个可编辑的交易表,余额到那时为止. ([xx]是我显示输入字段的方式.

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.

我正在使用Rails 3.2.12和Ruby 1.9.3.

I'm using Rails 3.2.12 and Ruby 1.9.3.

谢谢! 菲尔

推荐答案

如果我了解您要执行的操作,那么您将非常亲密.您只需要向下钻取一个级别即可访问表单构建器正在使用的模型对象:

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>

这篇关于如何使用Rails以嵌套形式访问模型的虚拟属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆