Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails json object with model associations

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
like image 648
Adam Sz. Avatar asked Jan 13 '23 08:01

Adam Sz.


1 Answers

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

like image 59
MrYoshiji Avatar answered Jan 23 '23 18:01

MrYoshiji