Nghĩ rằng tôi sẽ ném điều này ra có liên quan đến chủ đề này trong trường hợp ai đó tình cờ gặp nó.
Bạn nên tránh xa việc gọi các phạm vi từ trong các phương pháp mẫu. Bạn sẽ nhanh chóng tìm thấy chính mình gỡ lỗi các vấn đề hiệu suất. Phạm vi sẽ luôn luôn quay trở lại cơ sở dữ liệu bất kể nếu một mối quan hệ được bao gồm.
I.e.
class Show
has_many :episodes
def awesome_episodes
episodes.awesome # THIS IS BAD!!
# should stay in ruby land with episodes.select { |ep| ep.status == "awesome" }
# OR push a method #awesome? to the episode class and then the
# syntax becomes nicer: episodes.select(&:awesome?)
# This way, the onus is on the caller to include the relationship
end
end
class Episode
belongs_to :show
scope :awesome,()-> { where(status: 'awesome') }
end
shows = Show.includes(:episodes)
shows.map do |show|
show.awesome_episodes # fires a query every loop
end