4

i'm new to Ruby and Rails. I have a problem constructing json response for my service. I have two models:

class Transaction < ActiveRecord::Base
has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
has_and_belongs_to_many :transactions
end

So users have collection of transactions and transaction has collections of users. What i'm trying to do is return all transactions where asking user is involved and other users, which involved in all of transactions.

My json should look like this:

{"transactions":[{"name":"transaction1", "users":[{"userName":"user1"},{"userName":"user2"}]},{"name":"transaction2", "users":[{"userName":"user1"},{"userName":"user2"}]}]}

Here is my code:

@user = User.find_by_facebookId(params[:id])

#json = User.find_by_facebookId(params[:id], :include => :transactions).to_json( :include => :transactions )

if @user != nil
   render json: {"transactions" => @user.transactions.map do |transaction|
         transaction
   end
   }
else
  render json: {"transactions" => [{}]}
end
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
Adam Sz.
  • 152
  • 1
  • 2
  • 11

2 Answers2

8

You can do the following:

json_data = @user.transactions.map do |transaction|
  transaction.as_json(include: :users)
end
render json: { transactions: json_data }

Based on this question/answer: Rails Object Relationships and JSON Rendering

MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
  • Thanks! That almost do the job. I get only \ character For example: {"transactions":["{\"name\":\"test\",\"users\": ... – Adam Sz. Sep 19 '13 at 18:42
  • You may have to add a `.to_json` after the closing end keyword of the map to eliminate this escaping process – MrYoshiji Sep 19 '13 at 18:44
  • Nope, that's add anothe \. Maybe i should ovverride to_json methos in my class or something like that? But anyway, thanks for help. Edit: as_json works. – Adam Sz. Sep 19 '13 at 18:57
1

try this.

render json: { "transactions" => @user.transactions.map do |transaction|
                    JSON.parse(transaction.to_json(:include => :users))
               end
             }

It will be a hash instead of strings array.

Nate Cheng
  • 414
  • 6
  • 11