【问题标题】:Active record query for double many-to-many relationship双多对多关系的活动记录查询
【发布时间】:2015-12-07 21:41:37
【问题描述】:

我有一个 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) 在单个变量中获取特定公司所有汽车的最后位置

谁能帮我写这些查询。

提前致谢

【问题讨论】:

  • 在创建一些scopes 之后,我会做类似Company.with_name("Blabla Gmbh").cars.all_locations 的事情。
  • 你能帮我写下这个的范围吗?
  • 并非如此。我不知道您的表格列。我在之前的评论中发送给您的链接是一个很好的起点。

标签: ruby-on-rails activerecord


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多