我该如何将哈希数组保存到数据库中?

4
我使用nokogiri将XML文档解析成哈希数组:
helpers/countries.helper
module CountriesHelper

  def parse
    @countries = ['australia', 'canada', 'france']
    @countries.inject([]) do |memo, country|
    File.open("public/#{country}.xml") do |f|
    xml = Nokogiri::XML(f)
    path = "//country/stores/"
      memo << xml.xpath(path).map do |x|
           { 'country' => x.parent['country'],
           'store' => x['store']}
    end
   end
  end

# [{"country"=>"australia", "store"=>"store1"}, {"country"=>"france", "store"=>"store2"}]

我该如何将这个哈希数组格式保存到我的数据库中?假设我有两个模型:Country和Store。
3个回答

3

您可以将散列数组存储在数据库中的 text 字段中。

在迁移文件中可能如下所示:

create_table "your_table", force: true do |t|
  t.text "your_column_name"
end

或者,如果您已经在数据库中拥有表格,并且只想向表格添加新列:

class Migration0001
  def change
    add_column :your_table, :your_column_name, :text
  end
end

请注意,如果您想在数据库中保存Hash对象,并将列类型定义为:text,那么Rails应该能够正确地序列化它,您不需要在模型中显式使用serialize

但是,在您的情况下,这是一个Hash数组,因此需要保存Array对象到数据库中,所以您需要在模型中对该字段进行序列化:

serialize :your_column_name, Array

那么,您可以在数据库中保存一个哈希数组。希望这有所帮助。

3
你可以对属性进行序列化,这意味着将其保存为特定类型的对象。
#in your model
serialize :store_hashes, Array

该字段应该是数据库中的文本字段。我不知道在这种情况下是否是个好主意 - 我怀疑不是。但这就是如何将哈希数组保存到数据库中。

http://apidock.com/rails/ActiveRecord/Base/serialize/class


0
假设一个国家有很多商店。在数据库中存储哈希值几乎没有意义(我个人认为)。将其存储在单独的表中会更有意义,也更容易进行查询。
module CountriesHelper

  def parse
    @countries = ['australia', 'canada', 'france']
    @countries.inject([]) do |memo, country|
    File.open("public/#{country}.xml") do |f|
    xml = Nokogiri::XML(f)
    path = "//country/stores/"
      memo << xml.xpath(path).map do |x|
           { 'country' => x.parent['country'],
           'store' => x['store']}

      country = Country.find_by_name(x.parent['country'])
      if country.nil?
        country = Country.create(name: x.parent['country'])
      end
      country.stores.create(name: x['store'])
    end
   end
  end

数据库事务应该从模型中调用;你可以稍后重构。

class Country < ActiveRecord::Base
  has_many :stores
end


class Store < ActiveRecord::Base
  belongs_to :country
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接