1

在数据库(mySQL)中,我有一个名为的表tests和一个名为cars. 使用ActiveRecordgem,我为这些表添加了类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}
        ]}
     }
}
4

0 回答 0