如果您習慣使用腳手架,那麼我建議您生成兩個
交易支架:script/generate scaffold transaction financial_id:integer ...
bank_accounts:script/generate scaffold bank_account financial_id:integer ...
和財務script/generate scaffold financials ...
在您的交易模型,加入:
class Transaction < ActiveRecord::Base
belongs_to :financial
end
在你BANK_ACCOUNT模型中,補充一點:從你的財務
class Financial < ActiveRecord::Base
has_many :transactions
has_many :bank_accounts
end
現在控制器,你可以使用這樣的事情:
class Bank_account < ActiveRecord::Base
belongs_to :financial
end
在你的財務模型,添加此
def index
@financial = Financial.find(params[:id])
#This fetches all bank_accounts related to financial
@bank_accounts = @financial.bank_accounts
#This fetches all transactions related to financial
@transactions = @financial.transactions
end
在您的意見中,您可以通過執行此操作查看屬於某個財務的所有銀行賬戶:
<% @bank_accounts.each do |bank_account| -%>
<%=h bank_account.something_here %> <!-- something_here is the column name corresponding to your bank_account table. -->
<%=h bank_account.something_here %> <!-- something_here is the column name corresponding to your bank_account table. -->
<%=h bank_account.something_here %> <!-- something_here is the column name corresponding to your bank_account table. -->
.
.
.
<% end -%>
在你的意見,你可以通過添加類似查看全部屬於特定金融交易:
<% @transactions.each do |transaction| -%>
<%=h transaction.something_here %> <!-- something_here is the column name corresponding to your bank_account table. -->
<%=h transaction.something_here %> <!-- something_here is the column name corresponding to your bank_account table. -->
<%=h transaction.something_here %> <!-- something_here is the column name corresponding to your bank_account table. -->
.
.
.
<% end -%>
請記住,在創建一個新的事務/的BankAccount使用屬於特定金融的ID 。希望這可以幫助。乾杯! :)
我不確定這是否是實現這些模型關係的最佳方式。據推測,賬戶和交易具有一對多的關係。爲了創建控制器而強制它們成爲模型的子代,並且僅僅爲了顯示兩個相關模型的信息而將它們視爲一體,這比其他任何方面都更具有變通性。 – Shaun 2010-06-12 14:36:36
你說得對。但我只是想回答@ user363243面臨的直接問題,只記得一些X和Y模型與Z控制器綁定在一起。由於沒有明確提出,我沒有更多的推測。 :) – 2010-06-12 14:47:25
嘿,夥計們,感謝您的幫助!上述例子唯一的問題是,'財務'只是我分組bank_accounts及其相關交易的一種方式。我本可以稱之爲「銀行中心」或其他任何東西。這就是說,我實際上做不了像@financial = financial.find(params [:id]) – dingalingchickenwiing 2010-06-12 16:54:49