0

次のデータ モデルがあり、各モデルからの情報を含む 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 つすべてのテーブル (クライアント、ワークアウト、エクササイズ) からの情報を含むデータを返す方法がわかりません (プログラムとルーチンを介して結合されています)。これは可能ですか?そして、それはどのように行われますか?

4

2 に答える 2

2

まず、クエリで何が起こっているのかよくわかりません:

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

これで十分ではありませんか?

@client.workouts

さて、答えに進みます...私がまだフォローしていると仮定します:

ActiveRecord は、.to_jsonここで暗黙的に呼び出されるメソッドを提供します。明示的なバージョンは、例えば

render json: clients_workouts.to_json

それを知っていればto_json、API を調べることができます (非推奨として表示されていても、いくつかの優れたドキュメントがあります: http://apidock.com/rails/ActiveRecord/Serialization/to_json )。しかし、基本的には、答えはルート オブジェクト (私が信じているクライアント) から始めて、そこからオプション ハッシュに含まれるオブジェクトと属性/メソッドを構築することです。

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

必要に応じて、関連する各モデルに含まれる属性またはメソッドをカスタマイズできます。ドキュメントを少し掘り下げてください。楽しむ!

于 2013-09-01T05:31:08.850 に答える
0

非常に可能であり、これを利用するためのさまざまな方法があります。

1 つ目は、サード パーティのライブラリを使用せずに、n+1 の問題を解くかのようにインクルードを使用することです。</p>

よりクールなアプローチを使用し、アクティブ モデル シリアライザーを使用する

アクティブなモデル シリアライザー

于 2013-09-01T05:31:24.587 に答える