我有以下数据模型,并希望呈现一个包含来自每个模型的信息的 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
但是,我不知道如何返回包含所有三个表(客户、锻炼、锻炼)信息的数据(通过程序和例程连接)。这可能吗?它是如何完成的?