我在带有mongoid的轨道5上有父子模型。当我使用.includes
命令查询父项时,我可以看到rails尝试查询mongo db - 但结果json不返回子对象。
父模型:
class Activity
include Mongoid::Document
field :title, type: String
has_many :activity_pictures
end
儿童模特:
class ActivityPicture
include Mongoid::Document
field :name, type: String
belongs_to :activity, :class_name => 'Activity'
end
控制器方法:
def index
@activities = Activity.includes(:activity_pictures).all
end
def show
Activity.includes(:activity_pictures)
end
当然,我更新了activity_params:
def activity_params
params.require(:activity).permit(:title, :activity_pictures)
end
如何从http://localhost:3000/activities.json和单个对象链接获取完整的json数据?
答案 0 :(得分:0)
虽然使用includes
加载了关联,但您需要专门调用已加载的关联才能进行渲染。尝试
def index
@activities = Activity.includes(:activity_pictures).all
render json: @activities, include :activity_pictures
end
答案 1 :(得分:0)
margo的上述答案是正确的领导。我虽然使用jbuilder,所以解决方案是更改文件
index.json.jbuilder
如下:
json.array! @activities do |activity|
json.title activity.title
json.activity_pictures activity.activity_pictures do |activity_picture|
json.name activity_picture.name
end
end