2012-07-26 78 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