Programing

Rails 4에서 Model.scoped는 더 이상 사용되지 않지만 Model.all은이를 대체 할 수 없습니다.

lottogame 2020. 10. 15. 07:22
반응형

Rails 4에서 Model.scoped는 더 이상 사용되지 않지만 Model.all은이를 대체 할 수 없습니다.


Rails 4를 시작 Model.scoped하면 이제 더 이상 사용되지 않습니다.

DEPRECATION WARNING: Model.scoped is deprecated. Please use Model.all instead.

그러나, 거기에 차이점 Model.scopedModel.all입니다, scoped.scoped동안, 범위를 반환하는 all.all실행 쿼리.

레일즈 3 :

> Model.scoped.scoped.is_a?(ActiveRecord::Relation)
=> true

레일즈 4 :

> Model.all.all.is_a?(ActiveRecord::Relation)
DEPRECATION WARNING: Relation#all is deprecated. If you want to eager-load a relation, you can call #load (e.g. `Post.where(published: true).load`). If you want to get an array of records from a relation, you can call #to_a (e.g. `Post.where(published: true).to_a`).
=> false

다음과 scoped같이 조건이 있거나 아무것도하지 않을 때 반환되는 라이브러리 / 관심사에 대한 사용 사례가 있습니다 .

module AmongConcern
  extend ActiveSupport::Concern

  module ClassMethods
    def among(ids)
      return scoped if ids.blank?

      where(id: ids)
    end
  end
end

이것을 scoped변경 하면 스코프 체인에서 사용 된 all위치에 따라 임의의 문제가 발생 among합니다. 예를 들어, Model.where(some: value).among(ids)범위를 반환하는 대신 쿼리를 실행합니다.

내가 원하는 것은 ActiveRecord::Relation단순히 범위를 반환 하는 멱 등성 메서드입니다 .

여기서 무엇을해야합니까?


Rails 3과 4 모두에서 작동 where(nil)하는을 실제 대체하는 것 같습니다 scoped. :(


Rails 4.1 (베타 1)에서는 다음이 작동합니다.

Model.all.all.is_a?(ActiveRecord::Relation)
=> true

따라서이 문제는 수정 된 것으로 보이며 4.1.0 Model.scoped에서는 완전히 제거되었습니다.


주석 중 하나에서 언급 했듯이은 문서에 따라all 범위를 반환해야합니다 .

문서는 정확합니다. ActiveRecord :: Relation을 반환하지만 콘솔에서 보려면 세미콜론을 사용해야합니다.

pry(main)> u = User.all;

pry(main)> u.class

=> ActiveRecord::Relation::ActiveRecord_Relation_User

사용하는 where(nil)외에도 clone그것이 selfRelation 임을 알고 scoped있고 args없이 호출하는 것과 동일한 동작을 얻는 다면 호출 할 수 있습니다 . deprecation 경고는 없습니다.

편집하다

현재 범위를 파악하는 데 필요한 모든 곳에서 scoped사용하는 것을 좋아하지 않기 때문에 이제이 코드를 드롭 인 대체물로 사용 where(nil)하고 있습니다.

     # config/initializers/scoped.rb
     class ActiveRecord::Base
       # do things the modern way and silence Rails 4 deprecation warnings
       def self.scoped(options=nil)
         options ? where(nil).apply_finder_options(options, true) : where(nil)
       end
     end

아칸소 저자는 밖으로 영업 지점으로부터 비슷한 완료 뭔가를 할 수없는 이유를 나는 볼 수 없습니다 allscoped않습니다 하지 동일하게 동작합니다.

참고 URL : https://stackoverflow.com/questions/18198963/with-rails-4-model-scoped-is-deprecated-but-model-all-cant-replace-it

반응형