it-source

레일 직렬화를 사용하여 해시를 데이터베이스에 저장

criticalcode 2023. 6. 15. 21:56
반응형

레일 직렬화를 사용하여 해시를 데이터베이스에 저장

내 레일 앱의 여러 시도에 해시 매핑 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

원본:

자세한 정보: 레일즈 문서 & &amp; 피독

열이 다음인지 확인합니다.: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

반응형