0

我有一个连接我appointmentclient表的 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?

4

1 回答 1

-2

我的问题来自一个糟糕的设计,我使用RABL修复了我的糟糕设计。

于 2013-02-22T18:53:15.973 回答