简体   繁体   中英

rails render json with query

I would like to include a username (a column in the user table) for each review in the following json response

render json: Doctor.all, :include => :reviews

What's the best way to accomplish this? Should I include the username in the reviews table or make a query before returning the json?

The reviews table schema is includes content , user_id and doctor_id

If it helps, I've included the relations below

class Doctor < ActiveRecord::Base
  has_many :reviews
  has_many :users, through: :reviews
end

class Review <ActiveRecord::Base
  belongs_to :user
  belongs_to :doctor
end

class User < ActiveRecord::Base
  has_many :reviews
  has_many :doctors, through: :reviews
end

Thanks @ali in the comments.

I used :include => {:reviews => {:include => {:user => { :only => :username }}}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM