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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With