레일: 데이터베이스의 빈 문자열을 NULL로 강제 적용합니다.
ActiveRecord가 빈 문자열을 DB에 NULL로 저장하도록 강제하는 간단한 방법(설정 등)이 있습니까?
그 이유는 기본값이 없는 NULL 가능 문자열 열이 DB에 있는 경우 이 값을 설정하지 않은 새 레코드는 NULL을 포함하지만 이 값을 빈 문자열로 설정한 새 레코드는 NULL이 아니므로 데이터베이스 내의 불일치가 발생하기 때문입니다.
현재 모델에서는 다음과 같은 작업을 하고 있습니다.
before_save :set_nil
def set_nil
[:foo, :bar].each do |att|
self[att] = nil if self[att].blank?
end
end
효율적이지도 않고 드라이하지도 않습니다.이것을 하나의 방법으로 분류하여 Active Record에 혼합할 수 있지만, 그 전에 이 방법을 이미 알고 싶습니다.
네, 현재 유일한 옵션은 콜백을 사용하는 것입니다.
before_save :normalize_blank_values
def normalize_blank_values
attributes.each do |column, value|
self[column].present? || self[column] = nil
end
end
코드를 믹스로 변환하여 여러 모델에 쉽게 포함할 수 있습니다.
module NormalizeBlankValues
extend ActiveSupport::Concern
included do
before_save :normalize_blank_values
end
def normalize_blank_values
attributes.each do |column, value|
self[column].present? || self[column] = nil
end
end
end
class User
include NormalizeBlankValues
end
또는 ActiveRecord에서 정의할 수 있습니다.: 모든 모델에 탑재할 수 있습니다.
마지막으로 ActiveRecord에도 포함할 수 있습니다.:기본이지만 필요에 따라 활성화합니다.
module NormalizeBlankValues
extend ActiveSupport::Concern
def normalize_blank_values
attributes.each do |column, value|
self[column].present? || self[column] = nil
end
end
module ClassMethods
def normalize_blank_values
before_save :normalize_blank_values
end
end
end
ActiveRecord::Base.send(:include, NormalizeBlankValues)
class User
end
class Post
normalize_blank_values
# ...
end
이 보석이 효과가 있는지 시험해 보십시오.
https://github.com/rubiety/nilify_blanks
단순히 빈 문자열보다 DB NULL을 사용하는 경우 데이터베이스에 들어오는 빈 값을 0으로 저장하기 위한 프레임워크를 제공합니다.
Rails에서는 폼에서 모델을 저장하고 사용자가 값을 제공하지 않을 때 NULL 대신 빈 문자열이 데이터베이스에 기록됩니다(공백과 NULL을 혼동할 수 있습니다).이 플러그인을 사용하면 모델을 저장하기 전에 비워 두면 0으로 변환되는 특성(또는 모든 특성에서 예외) 목록을 지정할 수 있습니다.
속성만 공백에 응답합니까?값이 true일 경우 0으로 변환됩니다.따라서 값이 0인 정수 필드에서는 작동하지 않습니다.예를 들어...
또 다른 옵션은 후크에서 처리하는 것이 아니라 커스텀세터를 제공하는 것입니다.예:
def foo=(val)
super(val == "" ? nil : val)
end
제안:
# app/models/contact_message.rb
class ContactMessage < ActiveRecord::Base
include CommonValidations
include Shared::Normalizer
end
# app/models/concerns/shared/normalizer.rb
module Shared::Normalizer
extend ActiveSupport::Concern
included do
before_save :nilify_blanks
end
def nilify_blanks
attributes.each do |column, value|
# ugly but work
# self[column] = nil if !self[column].present? && self[column] != false
# best way
#
self[column] = nil if self[column].kind_of? String and self[column].empty?
end
end
end
necroposting 죄송합니다.여기서는 정확한 답변을 찾을 수 없습니다.영역을 지정해야 하는 필드를 지정하는 솔루션이 필요한 경우:
module EnforceNil
extend ActiveSupport::Concern
module ClassMethods
def enforce_nil(*args)
self.class_eval do
define_method(:enforce_nil) do
args.each do |argument|
field=self.send(argument)
self.send("#{argument}=", nil) if field.blank?
end
end
before_save :enforce_nil
end
end
end
end
ActiveRecord::Base.send(:include, EnforceNil)
이쪽:
class User
enforce_nil :phone #,:is_hobbit, etc
end
field1과 field2가 있다고 가정하면 특정 필드를 적용하는 것이 편리합니다.필드1은 SQL에 고유한 인덱스가 있지만 공백일 수 있으므로 강제해야 합니다(NULL은 SQL에 의해 고유하다고 간주되지 않음). 그러나 필드2의 경우 실제로는 신경 쓰지 않으며 이미 수십 개의 콜백 또는 메서드가 있습니다. 필드2가 "일 때 동작하지만 필드2가 "일 경우 어플리케이션을 에러 레이어 아래에 파고듭니다.nil
내가 직면했던 상황.
누군가에게 유용할 수 있습니다.
특성 Gem 제거
사용자 형태든 콘솔이든 레이크 작업이든 레코드를 저장할 때 자동으로 이 작업을 수행하는 편리한 보석이 있습니다.
이것은 strip_attributes라고 불리며, 사용법이 매우 간단하며, 개봉 즉시 기본값이 적용됩니다.
기본적으로는 거의 항상 수행해야 하는 다음 두 가지 주요 작업을 수행합니다.
선행 및 후행 공백 제거:
" My Value " #=> "My Value"
빈 문자열을 로 변환합니다.
NULL
:"" #=> NULL " " #=> NULL
설치하다
다음과 같이 gem 파일에 추가할 수 있습니다.
gem strip_attributes
사용.
선행/추적 공백을 제거하고 빈 문자열을 다음 모델로 변환할 수 있습니다.NULL
:
class DrunkPokerPlayer < ActiveRecord::Base
strip_attributes
end
고급 사용법
선행/추적 공백 유지 여부 등 예외를 처리하기 위해 모델별로 전달할 수 있는 추가 옵션이 있습니다.
GitHub 저장소의 모든 옵션을 여기에서 볼 수 있습니다.
https://github.com/rmm5t/strip_attributes#examples
속성이 DB에 저장되기 전에 속성을 정규화하기 위해 Atribute normalizer gem을 사용합니다.
언급URL : https://stackoverflow.com/questions/7202319/rails-force-empty-string-to-null-in-the-database
'programing' 카테고리의 다른 글
MySQL 쿼리 결과를 다른 테이블에 저장하는 방법 (0) | 2022.11.21 |
---|---|
왜 모든 서브쿼리는 키워드별로 주문하기 전에 select-statement로 실행됩니다.이러한 서브쿼리는 필요하지 않은 경우에도 실행됩니다. (0) | 2022.11.21 |
창을 삭제하는 방법.Nuxt의 Vuex에서 문제없이 __NUXT__ (0) | 2022.11.21 |
MySQL : ERROR 1215 (HY000) :외부 키 제약 조건을 추가할 수 없습니다. (0) | 2022.11.21 |
Vuejs 및 Vuex 어레이에 무선 입력 값만 입력하는 방법 (0) | 2022.11.21 |