如何通过has_many和belongs_to显示所有数据?

时间:2012-11-27 13:46:13

标签: ruby-on-rails ruby-on-rails-3 activerecord associations

我有两种型号:汽车和发动机。 一辆车必须有一个发动机。

我的模特协会

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:奔驰

3 个答案:

答案 0 :(得分:2)

 res = Car.joins(:engine).select("cars.id,cars.name,cars.model,engines.id,engines.name,...")

答案 1 :(得分: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

答案 2 :(得分:1)

Car.joins(:engine).includes(:engine).select("cars.name, engines.name")