双重多对多关系的活动记录查询

时间:2015-12-07 11:54:56

标签: ruby-on-rails activerecord

我有一个rails应用程序,其中我有三个模型

1)公司

2)车

3)位置

我的三个车型之间的关系是,公司有很多车,每辆车都有很多地方:

class Company < ActiveRecord::Base    
  has_many :cars    
end

class Car < ActiveRecord::Base    
  belongs_to :company
  has_many :locations    
end

class Location < ActiveRecord::Base
  belongs_to :car
end

现在我想写两个activerecord查询

1)在一个变量中获取特定公司所有汽车的所有位置

2)在一个变量中获取特定公司所有汽车的最后位置

任何人都可以帮我写这些查询。

提前致谢

1 个答案:

答案 0 :(得分:1)

class Company < ActiveRecord::Base    
  has_many :cars    
end

class Car < ActiveRecord::Base    
  belongs_to :company
  has_many :locations    
end

class Location < ActiveRecord::Base
  belongs_to :car
end

class Company < ActiveRecord::Base    
  has_many :cars
  has_many :locations, through: :cars    
end

class Car < ActiveRecord::Base    
  belongs_to :company
  has_many :locations    
end

class Location < ActiveRecord::Base
  belongs_to :car
end

1)在一个变量中获取特定公司所有汽车的所有位置

Company.where({...}).first.locations,或与您的范围有关 Company.with_name("Blabla Gmbh").locations

2)在一个变量中获取特定公司所有汽车的最后位置

Company.with_name("Blabla Gmbh").locations.last