2013-02-20 121 views
0

我已經在我的Rails應用程序以下型號:Rails的活動記錄查詢和JSON

class Transaction 
    belongs_to :category 
    has_one :group, :through => :category 

class Category 
    belongs_to :group 
    has_many :transactions 

class Group 
    has_many :categories 
    has_many :transactions, :through => :category 

在我的控制器如下:

@transactions = Transaction.includes(:category, :group).group("groups.id").sum("amount") 
respond_to do |format| 
    format.json{ 
    render :json => JSON.generate(@transactions.as_json(:include => [:category, :group])) 
    } 
end 

這將產生以下JSON(一個) :

{"1":2000,"3":5000,"2":1000} 

但是,我的目標是生產類似這個():

[{"group_id":1,"amount":2000},{"group_id":3,"amount":5000},{"group_id":2,"amount":1000}] 

上我如何從一個任何幫助將不勝感激。

回答

1

嘗試:

def user_transactions 
    @transactions = Transaction.includes(:category, :group).group("groups.id").sum("amount") 
    respond_to do |format| 
    format.html 
    format.json do 
     render :json => custom_json_for(@transactions) 
    end 
    end 
end 

private 
def custom_json_for(value) 
    list = value.map do |k,v| 
    { :group_id => k, 
     :amount=> v  
    } 
    end 
    list.to_json 
end 
+0

感謝您的幫助。但是,這給了我以下錯誤:'NoMethodError:[1,2000]的未定義方法'group_id':Array' – diasks2 2013-02-20 12:15:02

+0

用您希望的表的列名替換'group_id'。 – 2013-02-20 12:19:10

+0

如果我將其更改爲:'list = value.map do | k,v | {:group_id => k, :amount => v } end' – diasks2 2013-02-20 12:32:33