2017-08-09 17 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()} 

うまく動作します。レンダリング中にネストされたRails 4でレンダリングされない機能が含まれています。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 
    } 
} 

を取得していますしかし、私はちょうどstudentオブジェクトにuseridfirst_nameをしたいです。 なぜ入れ子のインクルードがここで動作しないのか、私は混乱しています。 あなたの助けに感謝します。 ありがとうございます。

答えて

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

関連する問題