본문 바로가기

Ruby On Rails/Model(ORM)

(4)
find_in_batches vs each_slice 모든 ids값을 가지고 오면 쿼리 오류가 발생할 수 있다. 그 이유에 대해서는 https://dexlee.tistory.com/109?category=1031550 여기에 에러 메시지와 함께 설명을 해놓았다. 그래서 이런 경우, 배치 함수를 사용해서 데이터를 가져와야 속도도 빠르고 안전하다. 1. find_in_batches(), in_batches() 두 함수의 약간의 차이점에 대해서는 다루지 않고 공통점에 대해서 다루고, 문제점을 정의하겠다. 이 두 함수는 실무에서 사용이 제한적이어야만 한다. 왜냐하면 모든 ids값을 가지고 limit을 사용해 데이터를 자른다. 1) 예시 BATCH_SIZE = 4 ids = (1..10).to_a sheets = [] Sheet.where(id: ids).find_..
batches를 사용하는 이유 1. 큰 크기의 ids 큰 크기의 ids(성능에 따라 다르겠지만 대략 100만개 이상)를 넘기면 쿼리를 처리하는 과정에서 오류가 발생할 수 있다. ActiveRecord::StatementInvalid: Mysql2::Error::ConnectionError: MySQL server has gone away from /Users/xxx/.rbenv/versions/2.6.6/lib/ruby/gems/2.6.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:131:in `_query' Caused by Mysql2::Error::ConnectionError: MySQL server has gone away from /Users/xxx/.rbenv/versions/2.6.6/lib/r..
preload vs includes vs eager_load vs joins 이 4가지의 차이점을 살펴보겠다. 1. preload 연관관계에 있는 테이블을 미리 로드해준다. includes와 default는 같지만 약간의 차이가 있다. 연관관계 로드할 때, 항상 query를 분리해서 요청한다. store = '도매' wholesale_stores = WholesaleStore.preload(store_number: [building_floor: :building]).where('store LIKE ?', "%#{store}%") 이렇게 호출하면 쿼리가. WholesaleStore Load (44.5ms) SELECT `wholesaleStore`.* FROM `wholesaleStore` WHERE (store LIKE '%도매%') StoreNumber Load (30.6ms)..
Model 정리 1. model&.other_model & : return empty string if don’t have any value there 만약 비어있는 값일 때, 에러를 내지 않는다. Ex) wholesale_store&.ssm_store_number 2. Model.where(id: id).first 리턴 값이 list이다. 그러므로 상대 쪽에 있는 유일한 값(PK)을 가져오고 싶을 땐 first를 써줘야 한다. 만약 배열로 받는 것이 싫다면 find를 써서 하나만 받아오는 방법도 있다. 3. Model.find(id: id) return variable 즉, list가 아닌 단일 값 리턴이다. 4. model.where(other model: {col: data}) https://stackoverflo..