【发布时间】:2013-01-10 07:33:50
【问题描述】:
我有一个特定的 ActiveRecord 范围来连接我的 appointment 和 client 表。当我使用它时,只有一个查询:
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?
【问题讨论】:
标签: ruby-on-rails json serialization rails-activerecord