Javier Antonini
Javier Antonini

Reputation: 137

How to make Rails as_json faster

I'm working on a REST server on Rails in which users can have a friendship relationship with other users. To represent this relationship I'm using a join table "friendships", which has an "status" attribute to indicate if the relationship has been accepted, refused, canceled, or is pending.

On my User model I have something like this:

has_many :friendships
has_many :friends, -> { where(friendships: {status: 2})}, through => :friendships
has_many :requests, -> { where(friendships: {status: 1})},
                   :class_name => "Friendship", :foreign_key => "friend_id"
has_many :pending_friends, :through => :requests, :source => :user

and other few more relationships to represent the inverse (when the user is the one that is asking and so). On my Friendship model:

belongs_to :user
belongs_to :friend, :class_name => "User"

Now what I want to do is to have a service in which an user can check all his friendships and friendship requests, and of course some data of the other user so I don't have to do extra requests for that. So what I am doing is this:

friendships = current_user.friendships.where(status: 2).includes(:friend)
              .as_json(include: {friend: {only: [:id, :username, :photo_url]}})

requests = current_user.requests.includes(:user)
           .as_json(include:  {user: {only: [:id, :username, :photo_url]}})

render json: {friendships: friendships, requests: requests}, status: 200

Now I have been testing and when a user has 1000 friendships relationships it can take up to 5 seconds to load this. But if I take away that only: [:id,..] from as_json it will run around 1 sec but it will have all the user's information. And if I completely remove the as_json it will run in 0.4 secs, but I will only have the information of the friendship, and will not include the information of the other user.

For the record I am building the same app on Laravel, I'm supposed to find out which framework/language is the best for our case. And in that Laravel app, since the ORM builds the objects in array structures and lets you decide what data to bring from the join table, it is easier to accomplish this in 0.5 seconds. So telling me that Rails is not so good for what I want to do and switch to Laravel is an acceptable response I guess.

Upvotes: 0

Views: 352

Answers (1)

rob
rob

Reputation: 2296

we had the same problem and switched to OJ (https://github.com/ohler55/oj).

its faster than the other engine. there are some performance tests on the github page

best

Upvotes: 1

Related Questions