다음 데이터 모델을 가지고 있으며 각 모델의 정보가 포함 된 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
그러나 (프로그램, 루틴을 통해 조인 된) 세 테이블 (클라이언트, 운동, 운동)의 정보가 포함 된 데이터를 반환하는 방법을 알지 못합니다. 이것이 가능한가? 그리고 어떻게 되었습니까?
@client.workouts는 거의 동일한 것을 반환합니다. 내 쿼리는 또한 워크 아웃 배열의 키로 클라이언트 ID를 반환했습니다. 당신의 솔루션은 제가 찾고있는 솔루션이었습니다. 나는 그것을 너무 복잡하게 만들고 있었다. 고맙습니다! – marianaiam