2012-08-31 13 views
0

我试图从我的模型中获取关联记录的所有记录,然后使用.to_json生成json。我正在使用Rails 2.3获取与关联的Model.all并返回为json

这里是一块模型的一部分:

class Currency 
    has_many :exchange_from, :class_name => "CurrencyExchange", :foreign_key => "currency_from_id", :dependent => :destroy 
    has_many :exchange_to, :class_name => "CurrencyExchange", :foreign_key => "currency_to_id", :dependent => :destroy 

这是代码,我认为将工作:

Currency.all(:include => [:exchange_from, :exchange_to]).to_json 

但结果是exacly 相同我会做简单的Currency.all.to_json。如果使用ActiveRecord无法实现我的目标,请指导我使用哪种SQL。

回答

2

这样做:

Currency.all(:include => [:exchange_from, :exchange_to]).to_json(:include => [:exchange_from, :exchange_to]) 

Documentation here.