2012-07-26 81 views
0

剛剛開始使用Ruby(無IT背景)並根據上一個問題/答案(link)重新啓動項目。我有以下情況可現:如何顯示來自相關表格的描述字段(2)

創建currencymaster表具有以下的列id:integerdescription:stringisocode:string藉此ID列由紅寶石創建。

創建currencyrates表有以下的列id:integerdominant:integerconverted:integerrate:decimal由此由紅寶石創建的ID列。

根據help on this site我創建了以下型號。 的型號/ currencymaster.rb看起來是這樣的:

class Currencymaster < ActiveRecord::Base 
    has_many :currency_rates_dominant, :validate => true, :class_name => 'Currencyrate' 
    has_many :currency_rates_converted, :validate => true, :class_name => 'Currencyrate' 
end 

的模型/ currencyrate.rb看起來是這樣的:

class Currencyrate < ActiveRecord::Base 
    belongs_to :currency_master_doms, :class_name => 'Currencymaster' 
    belongs_to :currency_master_convs, :class_name => 'Currencymaster' 
end 

我沒有在兩個控制器改變任何事情。

views \ currencyrates \ index.html.erb是通過Ruby自動生成的,並顯示記錄的值爲整數。我們的目標是顯示錶中的currencymaster.isocurrencyrate.dominantcurrencyrate.converted

非常感謝!

回答

0

我想你應該改變你的類是這樣的:

class Currencyrate < ActiveRecord::Base 
    belongs_to :currency_master_dom, :class_name => 'Currencymaster', :foreign_key => 'dominant' 
    belongs_to :currency_master_conv, :class_name => 'Currencymaster' , :foreign_key => 'converted' 
end 

之後,你應該這樣做:

rate = Currencyrate.first 
rate.currency_master_dom.iso 
rate.currency_master_conv.iso 

所有的約定不尊重。您應該使用dominant_idconverted_id作爲外鍵,CurrencyRateCurrencyMaster作爲類名,並且您不應該使用's',而使用belongs_to

+0

@ Dougui:再次感謝,我會嘗試一下,然後發佈代碼以檢查是否需要(請)。類名是在'generate scaffold'語句中由ruby創建的,之後我可以更改它們嗎? – jmk 2012-07-26 13:11:58

+0

是的,你可以。您還可以重新創建代碼,並且在生成腳手架時,可以像這樣添加資本:'rails generate scaffold CurrencyRate ...'。請參閱指南:http://guides.rubyonrails.org/command_line.html#rails-generate。 – Dougui 2012-07-26 13:18:40

+0

現在我用列:'id:integer','dominant_id:integer','converted_id:integer'和'rate:decimal'更改了表'currencyrate'。 – jmk 2012-07-26 13:24:30