我有一个连接我的appointment
和client
表的ActiveRecord范围。当我使用它时,只有一个查询:
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
运行时,我会得到两个额外的查询:
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
- client
联接。我在Appointment
上有更多关联,我需要包含这些关联,并且不能接受每个关联。
如何在不触发大量额外查询的情况下将结果集转换为JSON?