Reputation: 153
@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()}
Every thing working fine.
I'm getting this result
{
"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
}
}
But I just want id
and first_name
of user
in student
object.
I'm confuse that why nested include is not working here.
Your help will be appreciated.
Thanks in advance.
Upvotes: 1
Views: 348
Reputation: 15045
The problem is in this line:
render :json => {:students => @std.as_json(include: [:user.as_json(only: [:id, :first_name])]), :test => @test.as_json()}
According to the documentation, nesting inclusion is performed by:
object.as_json(include: { nested_object: { only: [:nested_object_field] } })
Hence, you'll need to correct the line to:
render :json => {:students => @std.as_json(include: { user: { only: [:id, :first_name] } }), :test => @test.as_json()}
Upvotes: 1