레일 직렬화를 사용하여 해시를 데이터베이스에 저장
내 레일 앱의 여러 시도에 해시 매핑 ID를 저장하려고 합니다.이 새 열을 수용하기 위해 데이터베이스로 마이그레이션:
class AddMultiWrongToUser < ActiveRecord::Migration
def self.up
add_column :users, :multi_wrong, :string
end
def self.down
remove_column :users, :multi_wrong
end
end
내 모델에는 다음이 있습니다.
class User < ActiveRecord::Base
serialize :multi_wrong, Hash
end
그러나 레일 콘솔을 사용하여 다음을 수행하여 테스트할 때:
user = User.create()
user.multi_wrong = {"test"=>"123"}
user.save
출력이 거짓입니다.여기서 무슨 일이 일어나고 있습니까?
열 유형이 잘못되었습니다.문자열 대신 텍스트를 사용해야 합니다.따라서 마이그레이션은 다음과 같이 수행해야 합니다.
def self.up
add_column :users, :multi_wrong, :text
end
그러면 Rails가 사용자를 위해 YAML로 올바르게 변환하고 올바른 직렬화를 수행합니다.문자열 필드는 크기가 제한되며 특히 작은 값만 포함합니다.
업데이트됨:
정확한 구현은 데이터베이스에 따라 다르지만 PostgreSQL은 이제json
그리고.jsonb
해시/객체 데이터를 기본적으로 저장하고 ActiveRecord로 JSON에 대해 쿼리할 수 있는 열!
마이그레이션을 변경하면 완료됩니다.
class Migration0001
def change
add_column :users, :location_data, :json, default: {}
end
end
원본:
열이 다음인지 확인합니다.:text
그리고 아닌:string
마이그레이션:
$ rails g migration add_location_data_to_users location_data:text
생성해야 할 항목:
class Migration0001
def change
add_column :users, :location_data, :text
end
end
강의 내용:
class User < ActiveRecord::Base
serialize :location_data
end
사용 가능한 작업:
b = User.new
b.location_data = [1,2,{foot: 3, bart: "noodles"}]
b.save
더 멋져요?!
postgresql hstore 활용
class AddHstore < ActiveRecord::Migration
def up
enable_extension :hstore
end
def down
disable_extension :hstore
end
end
class Migration0001
def change
add_column :users, :location_data, :hstore
end
end
hstore를 사용하여 직렬화된 필드에 속성을 설정할 수 있습니다.
class User < ActiveRecord::Base
# setup hstore
store_accessor :location_data, :city, :state
end
Rails 4에는 Store라는 새로운 기능이 있으므로 문제를 해결하는 데 쉽게 사용할 수 있습니다.액세스 권한을 정의할 수 있으며, 사용 가능한 공간이 충분하도록 직렬화된 저장소에 사용되는 데이터베이스 열을 텍스트로 선언하는 것이 좋습니다.원래 예:
class User < ActiveRecord::Base
store :settings, accessors: [ :color, :homepage ], coder: JSON
end
u = User.new(color: 'black', homepage: '37signals.com')
u.color # Accessor stored attribute
u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor
# There is no difference between strings and symbols for accessing custom attributes
u.settings[:country] # => 'Denmark'
u.settings['country'] # => 'Denmark'
언급URL : https://stackoverflow.com/questions/6694432/using-rails-serialize-to-save-hash-to-database
'it-source' 카테고리의 다른 글
Apache POI를 사용하여 Excel 파일에서 열을 가져오는 방법은 무엇입니까? (0) | 2023.06.15 |
---|---|
잘못된 http_host 헤더 (0) | 2023.06.15 |
fgetpos/fsetpos와 ftell/fseeek의 차이점 (0) | 2023.06.15 |
목록에서 여러 값의 구성원을 테스트하는 방법 (0) | 2023.06.15 |
오류 가져오기: '() => () => boolean' 유형의 인수를 'EffectCallback' 유형의 매개 변수에 할당할 수 없습니다. (0) | 2023.06.15 |