无法嵌套JSON Rails

我无法通过通过轨道关系嵌套具有has_many的对象。

我的模型如下所示:

class SessionDetail < ActiveRecord::Base
 has_many :session_enrollments, dependent: :destroy
 has_many :customers, through: :session_enrollments
end

class SessionEnrollment < ActiveRecord::Base
 belongs_to :customers   //column name is "customers_id"
 belongs_to :session_details //column name is "sessiondetails_id"
end

class Customer < ActiveRecord::Base
 has_many :session_enrollments
 has_many :session_details, through: :session_enrollments
end

我试图嵌套一个json对象来返回一个会话详细数组,一个客户的子数组和一个session_enrollments的子数组(一个对象)

我的控制器当前如下所示:

def return_trainers_sessions
  @trainer_requests = SessionDetail.where(trainers_id: params[:trainers_id], state:     "PENDING")

  unless (!@trainer_requests.any?)
    respond_to do |format|
    msg = {:status => "SUCCESS", :messages => "Requests Found", :requests => @trainer_requests.as_json(:includes => {:customers => {:include =>:session_enrollments}})}
     format.json  { render :json => msg } # don't do msg.to_json
  end

我也尝试过制作课堂教学方法,但只能尽可能地嵌套客户。

我最终没有返回客户或session_enrollments,所以我的json看起来像我从来没有将包含添加到.as_json的右侧


注意你的复数形式。

class SessionDetail < ActiveRecord::Base
  has_many :session_enrollments, dependent: :destroy
  has_many :customers, through: :session_enrollments
end

# a session enrollment belongs to a single customer, and a single session detail. Similarly
# the foreign key fields should be singular, customer_id, session_detail_id
class SessionEnrollment < ActiveRecord::Base
  belongs_to :customer   
  belongs_to :session_detail
end

class Customer < ActiveRecord::Base
  has_many :session_enrollments
  has_many :session_details, through: :session_enrollments
end
链接地址: http://www.djcxy.com/p/39535.html

上一篇: Unable to nest JSON Rails

下一篇: Filter parents by child attribute, but eager