program tip

Rails 3 + activerecord, 조건을 충족하는 모든 레코드에 대해 단일 필드를 "대량 업데이트"하는 가장 좋은 방법

radiobox 2020. 10. 16. 07:19
반응형

Rails 3 + activerecord, 조건을 충족하는 모든 레코드에 대해 단일 필드를 "대량 업데이트"하는 가장 좋은 방법


레일 3에서 activerecord를 사용하여 조건을 충족하는 모든 레코드에 대해 : hidden 필드를 TRUE 로 설정하는 단일 쿼리 방법이 있습니까? 예를 들어,:condition => [ "phonenum = ?", some_phone_number ]

단일 쿼리로이를 수행 할 수없는 경우 최적의 접근 방식은 무엇입니까?


조건에 대해 선택적 두 번째 매개 변수와 함께 update_all사용하십시오 .

Model.update_all({ hidden: true }, { phonenum: some_phone_number})

update_all은 레일 3의 조건을 허용하지 않습니다. 범위와 update_all의 조합을 사용할 수 있습니다.

Model.where(phonenum: some_phone_number).update_all(hidden: true)

참조 : http://m.onkey.org/active-record-query-interface


콜백을 트리거하려는 경우 :

class ActiveRecord::Base
  def self.update_each(updates)
    find_each { |model| model.update(updates) }
  end

  def self.update_each!(updates)
    find_each { |model| model.update!(updates) }
  end
end

그때:

Model.where(phonenum: some_phone_number).update_each(hidden: true)

참고 URL : https://stackoverflow.com/questions/4912510/rails-3-activerecord-the-best-way-to-mass-update-a-single-field-for-all-the

반응형