2

我有 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"
            }
         ]
    }, 

   ]
}
4

2 回答 2

0

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

嵌套属性允许您通过父项将属性保存在关联记录上。

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

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

于 2012-11-25T23:29:21.250 回答
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 来导入这些数据。祝你好运!

于 2012-11-26T13:24:42.207 回答