2013-09-01 2 views
0

다음 데이터 모델을 가지고 있으며 각 모델의 정보가 포함 된 json 해시를 렌더링하려고합니다. 예 : client.id, client.name_first, client, name_last, 각 클라이언트에 대한 모든 운동 설명 및 각 운동에 대한 각 운동 설명.여러 레일 모델 has_many : 관계를 통해 json으로 출력

class Client < ActiveRecord::Base 
    belongs_to :account 
    belongs_to :trainer 
    has_many :programs 
    has_many :workouts, :through => :programs 
end 

class Workout < ActiveRecord::Base 
    has_many :programs 
    has_many :clients, :through => :programs 
    has_many :routines 
    has_many :exercises, :through => :routines 
end 

class Exercise < ActiveRecord::Base 
    has_many :routines 
    has_many :workouts, :through => :routines 
end 

내 데이터베이스 마이그레이션 : 나는 특정 클라이언트에 대한 운동을 반환 할 수 있어요

class CreateClients < ActiveRecord::Migration 
    def change 
    create_table :clients do |t| 
     t.integer :account_id 
     t.integer :trainer_id 
     t.string :name_first 
     t.string :name_last 
     t.string :phone 

     t.timestamps 
    end 
    end 
end 

class CreateWorkouts < ActiveRecord::Migration 
    def change 
    create_table :workouts do |t| 
     t.string :title 
     t.string :description 
     t.integer :trainer_id 

     t.timestamps 
    end 
    end 
end 

class CreateExercises < ActiveRecord::Migration 
    def change 
    create_table :exercises do |t| 
     t.string :title 
     t.string :description 
     t.string :media 

     t.timestamps 
    end 
    end 
end 

:

@client = Client.find(params[:id]) 
clients_workouts = @client.workouts.select('workouts.*,programs.client_id').group_by(&:client_id) 
render json: clients_workouts 

그리고 특정 운동을위한 운동을 반환 할 수 있어요 :

@workout = Workout.find(params[:id]) 
exercises_workouts = @workout.exercises.select('exercises.*, routines.workout_id').group_by(&:workout_id) 
render json: exercises_workouts 

그러나 (프로그램, 루틴을 통해 조인 된) 세 테이블 (클라이언트, 운동, 운동)의 정보가 포함 된 데이터를 반환하는 방법을 알지 못합니다. 이것이 가능한가? 그리고 어떻게 되었습니까?

답변

2

첫째, 쿼리에 무슨 일이 일어나고 있는지 정말 모르겠어요 :

clients_workouts = @client.workouts.select('workouts.*,programs.client_id').group_by(&:client_id) 

이 충분이 아닌가?

@client.workouts 

자, 대답에 ... 난 아직도 다음있어 가정 :

액티브는 .to_json 방법, 암시 적으로 여기에 호출되고 있는지입니다 제공합니다. 명시적인 버전은 예 : 그것을 알고

render json: clients_workouts.to_json 

, 당신은 (: http://apidock.com/rails/ActiveRecord/Serialization/to_json를 여기가되지 않는 것으로 표시에도 불구하고 좋은 문서의) API에서 to_json를 찾아 볼 수 있습니다. 그러나 기본적으로 대답은 루트 객체 (내가 믿는 클라이언트)로 시작하여 옵션 해시에 포함 된 객체와 속성/메소드를 빌드하는 것입니다.

render json: @client.to_json(include: { workouts: { include: :exercises } }) 

필요한 경우 각 관련 모델의 속성 또는 메소드를 사용자 정의 할 수 있습니다. 문서를 조금만 살펴보십시오. 재미있어!

+0

@client.workouts는 거의 동일한 것을 반환합니다. 내 쿼리는 또한 워크 아웃 배열의 키로 클라이언트 ID를 반환했습니다. 당신의 솔루션은 제가 찾고있는 솔루션이었습니다. 나는 그것을 너무 복잡하게 만들고 있었다. 고맙습니다! – marianaiam

0

매우 가능성이 있으며이를 선호하는 방법이 다릅니다.

하나, 어떤 제 3 자 라이브러리를 사용하는 것입니다 당신이 활성 모델 시리얼

Active Model Serializers

을의 n + 1 문제 나 ...

를 사용하여 훨씬 쿨러 접근 방식을 해결하고 사용하는 것처럼, 포함하지 않고

관련 문제