rails渲染json查询

时间:2014-10-26 19:49:16

标签: ruby-on-rails json

我想在以下json响应中为每个评论添加一个用户名(用户表中的一列)

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

实现这一目标的最佳方法是什么?我应该在评论表中包含用户名还是在返回json之前进行查询?

评论表架构包括contentuser_iddoctor_id

如果有帮助,我已经包含了下面的关系

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

1 个答案:

答案 0 :(得分:0)

在评论中感谢@ali。

我使用了:include => {:reviews => {:include => {:user => { :only => :username }}}}