2013-03-04 63 views
1

我有一個基本的嵌套窗體。我想訪問嵌套窗體模型的虛擬屬性。如何使用Rails以嵌套形式訪問模型的虛擬屬性

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> 

除了v實際屬性錯誤,此表單按預期工作。

該代碼應該產生一個可編輯的交易表,其中的餘額至此爲止。 ([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。

謝謝! 菲爾

回答

1

如果我明白你想要做什麼,你就非常接近。您只需向下鑽取一個級別即可訪問表單構建器正在使用的模型對象:

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

就是這樣!謝謝丹。我忘了所有關於.object。 – nevieandphil 2013-03-05 07:20:07