appointment
とclient
テーブルを結合する特定のActiveRecordスコープがあります。私がそれを使用するとき、たった1つのクエリがあります:
1.9.2p290 :071 > reload!;Appointment.for_day(Time.zone.today).full.first
Reloading...
Appointment Load (6.9ms) SELECT "appointment".* FROM "appointment" JOIN client ON client.id = appointment.client_id
LEFT JOIN payment ON payment.appointment_id = appointment.id WHERE (start_time between '2013-01-26 05:00:00.000000' and '2013-01-27 04:59:59.000000' and is_cancelled = false) ORDER BY start_time asc LIMIT 1
=> #<Appointment id: 10137, start_time: "2013-01-26 13:00:00", created_at: "2012-07-16 18:01:21", updated_at: "2012-07-16 18:01:21", stylist_id: 88, client_id: 398, recurring: false, appointment_id: nil, is_cancelled: false, tip: #<BigDecimal:107ea1d68,'0.0',9(18)>, repeats_every_how_many_weeks: 1, recurrence_rule_hash: "qkebvqfsprmkbcsccsifbbumazooampyxzkyehqommbjmdsmmc", can_repeat: true, notes: "", time_block_type_id: 2, length: 60>
同じことを実行して実行するとto_json
、2つの追加クエリが発生します。
1.9.2p290 :072 > reload!;Appointment.for_day(Time.zone.today).full.first.to_json
Reloading...
Appointment Load (6.7ms) SELECT "appointment".* FROM "appointment" JOIN client ON client.id = appointment.client_id
LEFT JOIN payment ON payment.appointment_id = appointment.id WHERE (start_time between '2013-01-26 05:00:00.000000' and '2013-01-27 04:59:59.000000' and is_cancelled = false) ORDER BY start_time asc LIMIT 1
Client Load (0.3ms) SELECT "client".* FROM "client" WHERE "client"."id" = 398 LIMIT 1
Address Load (0.3ms) SELECT "address".* FROM "address" WHERE "address"."id" = 10 LIMIT 1
=> "{\"appointment_id\":null,\"can_repeat\":true,\"client_id\":398,\"created_at\":\"2012-07-16T14:01:21-04:00\",\"id\":10137,\"is_cancelled\":false,\"length\":60,\"notes\":\"\",\"recurrence_rule_hash\":\"qkebvqfsprmkbcsccsifbbumazooampyxzkyehqommbjmdsmmc\",\"recurring\":false,\"repeats_every_how_many_weeks\":1,\"start_time\":\"2013-01-26T08:00:00-05:00\",\"stylist_id\":88,\"time_block_type_id\":2,\"tip\":\"0.0\",\"updated_at\":\"2012-07-16T14:01:21-04:00\",\"client\":{\"active\":true,\"address_id\":10,\"created_at\":\"2012-05-22T11:48:44-04:00\",\"email\":\"\",\"id\":398,\"name\":\"No client\",\"notes\":\"\",\"phone\":\"\",\"salon_id\":29,\"updated_at\":\"2012-05-22T11:48:44-04:00\",\"wants_email_reminders\":false}}"
ActiveRecordがテーブルに対して別のクエリを実行したいのはイライラします。client
私はすでにappointment
-joinを実行しているからclient
です。含める必要のある関連付けは他にもたくさんAppointment
あり、それぞれに個別のクエリを設定することはできません。
大量の余分なクエリをトリガーせずに結果セットをJSONに変換するにはどうすればよいですか?