我无法通过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的右侧
答案 0 :(得分:0)
注意你的复数。
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