使用ActiveRecord从MySQL表返回分层数据

时间:2013-05-06 17:09:48

标签: ruby json activerecord hierarchy

在数据库(mySQL)中,我有一个名为tests的表和一个名为cars的相关(通过FK)表。使用ActiveRecord gem,我在schema.rb中添加了这些表的类:

class Test < ActiveRecord::Base
  has_many :cars
end

class Car <ActiveRecord::Base
  belongs_to :tests
end

运行以下简单脚本:

puts "the Test Object identified by name 'Rob'"
puts Test.find_by_name("Rob").to_json
puts "Cool - no problem!"
puts ""
puts "the cars that belong to Rob 
puts Test.find_by_name("Rob").cars.to_json
puts "Correct - Rob has 2 cars "

产生预期结果:

the Test Object identified by name 'Rob'
{"test":{"idtest":1,"name":"Rob","rugby_team":"Lions"}}
Cool - no problem!

the cars that belong to Rob 
[
    {"car":{"car_make":"Honda","idcars":1,"test_id":1}},
    {"car":{"car_make":"Nissan","idcars":7,"test_id":1}}
]
Correct - Rob has 2 cars!

我想到第二个查询应该返回看起来像这样的json(Car个对象数组):

{cars: [ 
    {"car_make":"Honda","idcars":1,"test_id":1},
    {"car_make":"Nissan","idcars":7,"test_id":1}
    ]}

问题1:在上面的示例中我做错了什么?

问题2:我必须更改什么才能将属于Rob的汽车作为第一个测试对象的一部分? (如下例所示)

我需要退回的内容:

{"test":{"idtest":1,"name":"Rob","rugby_team":"Lions", 
    {cars: [ 
        {"car_make":"Honda","idcars":1,"test_id":1},
        {"car_make":"Nissan","idcars":7,"test_id":1}
        ]}
     }
}

0 个答案:

没有答案