0

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)

alybadawy
  • 489
  • 2
  • 7
  • 13

3 Answers3

2

if your Comment belongs_to User and your User has many comments

you can use this query:

Comment.find(:all, :joins => :user)
2

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...

Marek Takac
  • 3,002
  • 25
  • 30
  • I know I accepted this answer a long time ago; actually over 3 years ago. but would like to thank you again for it :) – alybadawy Aug 05 '16 at 15:37
0

User.all.select('*').joins(:comments) The select method is needed to return all fields. I'd also get in practice of starting with parent table.

Natus Drew
  • 1,876
  • 1
  • 21
  • 23