2015-10-19 90 views
1

我用引入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"}] 

我怎样才能挽救这个数组哈希格式的到我的数据库?比方说,我有两个模型国家和商店。

回答

0

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

但是,在你的情况下,它的HashArray,所以它是一个Array对象需要保存在数据库中,所以你需要序列化领域的模型:

serialize :your_column_name, Array 

这样,您可以在数据库中保存ArrayHashes。希望这可以帮助。

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 
2

您可以serialize属性,这意味着将其保存为特定类型的对象。

#in your model 
serialize :store_hashes, Array 

该字段应该是数据库中的text字段。我不知道在这个特殊情况下这是否是一个好主意 - 我怀疑它不是。但这就是如何将一列哈希存储到数据库的方式。

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