如何在Rails中存储嵌套的json数据?

时间:2012-11-25 19:25:21

标签: ruby-on-rails ruby ruby-on-rails-3 json

我有3个型号:

class Depot < ActiveRecord::Base
    has_many :car_amounts
    has_many :cars, :through => :car_amounts
end

class CarAmount < ActiveRecord::Base
  belongs_to :depot
  belongs_to :car
end

class Car < ActiveRecord::Base
  has_many :car_amounts
  has_many :depots, :through => :car_amounts
end

存储json参数的最佳方法是什么,它包含库,数量和汽车数据。像这样:

{
"Depots": {
    "title": "Dealer1"
},
"Amounts": [
    {
        "amount": "1"
        "car": [
            {
                "Type": "supercar1"
            }
         ]
    }, 
    {
        "amount": "5"
        "car": [
            {
                "Type": "supercar2"
            }
         ]
    }, 

   ]
}

2 个答案:

答案 0 :(得分:0)

我有点不清楚你的问题是什么,但我认为你可能正在寻找accepts_nested_attributes_for。文档可以在http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html找到。来自文档:

  

嵌套属性允许您通过父级保存关联记录的属性。

例如,您可以在accepts_nested_attributes_for :cars模型中添加Depots。虽然它与上面显示的JSON不太一致,但它适用于一般的想法。

如果这不是您的问题,请发表评论,我会澄清。

答案 1 :(得分:0)

如果这个数据需要在您的数据库中,那么我将“播种”数据并将其导入您的数据库。您可以创建文件db / seed.rb,并假设我想将学生导入我的数据库。我已经创建/迁移了学生模型。在我的seed.rb中,我会做类似......

students = ActiveSupport::JSON.decode(File.read('db/students.json'))

students.each do |a|
     Student.find_or_create_by_id_number(:id_number => a['id_number'], :username => a['username'], :first_name => a['first_name'], :last_name => a['last_name'])
end

......我的students.json看起来像......

 [
{"id_number": "00xx280","username": "jesxxne","first_name": "Jessie","last_name": "Lane","email": "jesxxane@xx.edu","phone_number": "602-321-6693","is_active": true ,"last_four": "1944" },
{"id_number": "11xx2","username": "jamxxacqua","first_name": "James","last_name": "Bevixxua","email": "jamesbxxacqua@xx.edu","phone_number": "828-400-5393","is_active": true ,"last_four": "5422" }
 ]

现在您可以运行rake db:seed来导入此数据。祝你好运!