如何将哈希数组保存到db?

时间:2015-10-19 14:13:49

标签: ruby-on-rails ruby hash

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

助手/ 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 个答案:

答案 0 :(得分:2)

您可以#in your model serialize :store_hashes, Array 一个属性,这意味着将其另存为特定类型的对象。

text

该字段应该是数据库中的{{1}}字段。我不知道在这个特定情况下这是不是一个好主意 - 我怀疑它不是。但这就是如何将数组哈希值保存到数据库中。

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

答案 1 :(得分:1)

您可以将哈希数组存储在数据库的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

但是,在你的情况下,它是Array的{​​{1}},所以它是一个需要保存在数据库中的Hash对象,所以你需要序列化你的字段模型:

Array

这样,您可以在数据库中保存serialize :your_column_name, Array Array。希望这会有所帮助。

答案 2 :(得分: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

数据库事务是从Model调用的;你以后可以重构。

class Country < ActiveRecord::Base
  has_many :stores
end


class Store < ActiveRecord::Base
  belongs_to :country
end