Search code examples
ruby-on-railsjsonapiruby-grape

Simple join between two tables in Rails


I am building a rails application to work as a back end for APIs. (using grape APIs) I have two tables (user, comment) where a user has many comments and a comment belongs to one users.

I am trying to return all comments, and within the Comment object, i want to show the User object for the user who created that comment.

I tried:

Comment.includes(:user)

and

Comment.joins(:user).includes(:user)

And none of them managed to return the sub-object. only returns the Comment object (which has user_id) attribute).

Is there any way to achieve that in a JSON format (as mentioned, I use GRAPE)


Solution

  • You can use to to_json or as_json with :include option. In your api:

    resources :comments
      get :id do
        Comment.includes(:user).find(params[:id]).to_json(include: :user)
      end
    end
    

    However, sooner or later you will probably need more control over the json responses generated by your API. I would suggest you to take a look at grape-rabl gem (or some other solution for building json - there are plenty of them out there). It will grant you much finer control...