在数据库(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}
]}
}
}