diasks2
diasks2

Reputation: 2142

Rails Active Record Query and JSON

I have the following models in my Rails application:

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

In my controller is the following:

 @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

This produces the following json (A):

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

However, my goal is to produce something like this (B):

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

Any help on how I can go from A to B would be greatly appreciated.

Upvotes: 0

Views: 1818

Answers (2)

sjain
sjain

Reputation: 23344

Try:

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

Upvotes: 1

Jesper
Jesper

Reputation: 4555

If you're doing a lot a JSON-serialization, I would recommend you to take a look at ActiveModelSerializers: https://github.com/rails-api/active_model_serializers

Upvotes: 0

Related Questions