Unable to nest JSON Rails

I'm having trouble nesting my objects that have a has_many through relationships via rails.

My models look like this:

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

I'm trying to nest a json object to return an array of session details, with a sub array of customers and a subarray (one object) of session_enrollments

My controller current looks like this:

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

I've also tried making a class method, but am only able to get as far as nesting the customers.

I end up returning no customers or session_enrollments, so my json just looks like I never added the includes to the right hand of .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/39536.html

上一篇: WPF获取鼠标下的元素

下一篇: 无法嵌套JSON Rails