In an app that was recently ported from Rails 3 to Rails 4, I have a model called MeetingSeries with the following relation:
has_many :meetings, :foreign_key => :series_id
The Meetings model has the following scope:
scope :future, -> { where("start_time is not NULL and end_time > ?", DateTime.now())}
So if I have a particular meeting series:
@m = MeetingSeries.find(42)
I can grab all the meetings from that series like this:
@m.meetings
In this case, I correctly get a small number of meetings that are in just the specified series. However, when I use the scope:
@m.meetings.future
I suddenly get all future meetings, not just the ones in the specified series. The SQL queries that get built for these two are very different and make obvious the fact that the series ID is not part of the query:
irb(main):003:0> @m.meetings.count()
(1.5ms) SELECT COUNT(*) FROM `meetings` WHERE `meetings`.`type` IN ('Meeting') AND `meetings`.`series_id` = 9856
=> 78
Versus:
irb(main):004:0> @m.meetings.future.count()
(16.7ms) SELECT COUNT(*) FROM `meetings` WHERE `meetings`.`type` IN ('Org::Happenings::ScheduledHappening', 'Org::Happenings::RoomBooking', 'Org::Happenings::Meeting', 'Org::Happenings::Unavailability', 'Meeting', 'Unavailability') AND (start_time is not NULL and end_time > '2018-08-16 15:35:09.609774')
=> 3422
This behaved properly under Rails 3, so I gather the erroneous behavior stems from some difference in either the way scopes work, or ActiveRecordRelations work, in Rails 4. Any ideas?
Aucun commentaire:
Enregistrer un commentaire