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

pyf*_*l88 5 ruby hash ruby-on-rails

我使用 nokogiri 将 xml 文档解析为哈希数组:

助手/国家.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"}]
Run Code Online (Sandbox Code Playgroud)

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

K M*_*lam 4

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

您的迁移文件中类似这样的内容:

create_table "your_table", force: true do |t|
  t.text "your_column_name"
end
Run Code Online (Sandbox Code Playgroud)

或者,如果数据库中已有该表,并且只想将新列添加到该表中:

class Migration0001
  def change
    add_column :your_table, :your_column_name, :text
  end
end
Run Code Online (Sandbox Code Playgroud)

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

但是,在您的情况下,它是一个Arrayof Hash,因此它是一个Array需要保存在数据库中的对象,因此您需要序列化模型中的字段:

serialize :your_column_name, Array
Run Code Online (Sandbox Code Playgroud)

这样,您就可以在数据库中保存一个Arrayof 。Hashes希望这可以帮助。