2017-08-09 44 views
1
@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()} 

每件事情都可以正常工作。在渲染JSON期间嵌套包含不能在Rails 4中工作

我得到这个结果

{ 
    "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 
    } 
} 

但我只是想useridfirst_namestudent对象。 我很困惑,为什么嵌套include不在这里工作。 您的帮助将不胜感激。 在此先感谢。

回答

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()} 
+0

我的错误。谢谢你的帮助。 – Taimoor