简体   繁体   中英

has_many with a scope super slow with STI

class User < ApplicationRecord
  has_many :buckets, -> { order(ranked_row: :asc) }
  delegate :incomes, :fixed_costs, :financial_goals, to: :buckets

  ...
end

I have Buckets, that are STI'd. If I add that scope to the has_many, my page takes forever on 9 records, and seems to be loading something that should be cached

74s ...

If I remove the scope, all is well

3秒...

Any idea how the scope on the has_many is affecting the STI?? ranked_row has an index, but it's the same, regardless. I am using active_model_serializers, but I'm not sure if there's a correlation.

Update

Definitely something with active_model_serializers. ActiveModel::SerializableResource.new(user) is in the controller, and bogs down in the console, too. I removed everything from the from the serializer, and calling the scoped has_many is the thing. I'll hit up github.

Code

https://gist.github.com/dudo/f25767f00c874842a005

That's the smallest bit of code I could get to cause the issue. Again, It works fine without the scope on the has_many, and it also works with removing the percent_complete method from Bucket... that method doesn't look too nasty. What could be in that included_transactions method that's bringing it to a crawl when a scope is present??

When adding scope to a has_many you need to explicitly declare the inverse_of .

https://github.com/rails/rails/blob/7f18ea14c893cb5c9f04d4fda9661126758332b5/guides/source/4_1_release_notes.md

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM