Question

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)

Was it helpful?

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

OTHER TIPS

if your Comment belongs_to User and your User has many comments

you can use this query:

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top