@test = Test.find(params[:test_id].to_i)
group_tests_id = @test.group_tests.map(&:group_id)
@std = Student.joins(:group_students).where("group_id IN (?)",group_tests_id).uniq
render :json => {:students => @std.as_json(include: [:user.as_json(only: [:id, :first_name])]), :test => @test.as_json()}
每件事情都很好。
我收到了这个结果
{
"students": [
{
"id": 38,
"user_id": 34,
"created_at": "2017-08-07T12:30:02.120+05:00",
"updated_at": "2017-08-07T12:30:02.120+05:00",
"user": {
"id": 34,
"username": "taimoor123",
"created_at": "2017-08-07T12:30:02.067+05:00",
"updated_at": "2017-08-07T12:33:19.273+05:00",
"first_name": "Muhammad Taimoor",
"second_name": "Sultani",
"school_name": "Moon Public School",
"section_name": "Blue 10th",
"gender": "Male",
"age": 23,
"role": "Student",
"school_id": 1,
"section_id": 2,
}
}
],
"test": {
"id": 33,
"name": "Test 8/7/2017",
"attempt_time": 15,
"teacher_id": 1
}
}
但我只想在id
对象中first_name
和user
student
。
我很困惑,为什么嵌套包含在这里不起作用。
我们将不胜感激。
提前致谢。
答案 0 :(得分:1)
问题出在这一行:
render :json => {:students => @std.as_json(include: [:user.as_json(only: [:id, :first_name])]), :test => @test.as_json()}
根据documentation,嵌套包含是通过以下方式执行的:
object.as_json(include: { nested_object: { only: [:nested_object_field] } })
因此,您需要将该行更正为:
render :json => {:students => @std.as_json(include: { user: { only: [:id, :first_name] } }), :test => @test.as_json()}