Rails Active Record Query和JSON

时间:2013-02-20 11:43:27

标签: ruby-on-rails json rails-activerecord

我的Rails应用程序中有以下模型:

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( A ):

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

但是,我的目标是制作这样的东西( B ):

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

对于如何从 A B 的任何帮助将不胜感激。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

如果你做了很多JSON序列化,我建议你看一下ActiveModelSerializers: https://github.com/rails-api/active_model_serializers