1

我有两个模型:汽车和发动机。一辆车必须有一个引擎。

我的模特协会

class Car < ActiveRecord::Base
  belongs_to :engine

  attr_accessible :name, :engine_id              
end

class Engine < ActiveRecord::Base
  has_many :cars

  attr_accessible :name
end

我知道如何通过 Car 显示引擎数据:

Car.first.engine

这返回

irb(main):001:0> Car.first.engine
  ←[1m←[36mCar Load (0.0ms)←[0m  ←[1mSELECT "cars".* FROM "cars" LIMIT 1←[0m
  ←[1m←[35mEngine Load (0.0ms)←[0m  SELECT "engines".* FROM "engines" WHERE "engines"."id" = 1 LIMIT 1
=> #<Engine id: 1, name: "Benzine", created_at: "2012-11-27 12:09:08", updated_at: "2012-11-27 12:09:08">

但是如何同时展示汽车和发动机呢?

示例:car_id:1,car_name:奥迪,engine_name:Benzine

4

3 回答 3

2
 res = Car.joins(:engine).select("cars.id,cars.name,cars.model,engines.id,engines.name,...")
于 2012-11-27T18:07:54.320 回答
1
Car.joins(:engine).includes(:engine).select("cars.name, engines.name")
于 2012-11-28T07:11:59.930 回答
1

我想说最简单的解决方案是在您的模型中创建自定义方法。例如,在您的汽车模型 (car.rb) 中,您可以尝试以下操作:

  def info
    # as a string
    return "car: " + self.name + ", engine: " + self.engine.name
    # as a hash
    return { "car" => self.name, "engine" => self.engine.name }
  end

那么你就可以打电话给 Car.first.info

于 2012-11-27T13:58:29.493 回答