次のデータ モデルがあり、各モデルからの情報を含む json ハッシュをレンダリングしたいと考えています。たとえば、client.id、client.name_first、client、name_last、各クライアントのすべてのワークアウトの説明、および各ワークアウトの各エクササイズの説明です。
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
ただし、3 つすべてのテーブル (クライアント、ワークアウト、エクササイズ) からの情報を含むデータを返す方法がわかりません (プログラムとルーチンを介して結合されています)。これは可能ですか?そして、それはどのように行われますか?