-->

如何访问模式的虚拟属性的嵌套形式使用Rails(How to access virtual attr

2019-10-17 18:35发布

我有一个基本的嵌套形式。 我想访问的嵌套形式的模型虚拟属性。

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
  ...

在嵌套形式我想提出这样的:

<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>

我想下面给我的平衡日期。

nested_f.balance_to_date(:日)

或者能够像做

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

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

除了虚拟属性的错误,这种形式按预期工作。

该代码应该产生交易的可编辑的表格与平衡到这一点。 ([XX]是我的表示输入字段的方式)。

   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

如何访问和显示模式,并从当前正在显示的记录日期的虚拟属性的任何意见将非常感激。 我希望我没有重复前一个问题。

我使用的Rails 3.2.12和Ruby 1.9.3。

谢谢! 菲尔

Answer 1:

如果我理解你想要做什么,你是非常接近。 你只需要钻下调一个等级至访问表单生成器是使用模型对象:

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


文章来源: How to access virtual attributes of model in a nested form with Rails