【问题标题】:How to get objects related to an "ancestor" through one of its "descendants"如何通过其“后代”之一获取与“祖先”相关的对象
【发布时间】:2015-11-29 15:02:54
【问题描述】:

我有以下相关模型:

Country 
  has_many :states

State 
  belongs_to :country
  has_many :counties

County 
  belongs_to :State
  has_many :municipalities
  has_many :cities, through: :municipalities

City
  has_many :municipalities
  has_many :counties, through: :municipalities 

Municipality
  belongs_to :county
  belongs_to :city

我希望能够调用@country.cities 并让它通过其相关对象返回属于一个国家的所有城市。

有没有人看到或写过一个好帮手?还是有这样做的传统方法?现在我所拥有的最好的是像

  def country_cities(country)
    country.municipalities.each do |municipality|
      municipality.city
    end
  end

我对我可能遗漏了一些简单的事实持开放态度,但我已经详细阅读了活动记录文档,并且似乎活动记录在构建 SQL 查询时使用了 belongs_to 帮助器,所以 has_many 到关系打破了向下的“链条”,您必须像这样@country.municipalities.individual_municipality.cities

我正在寻找更优雅/更简单的解决方案

与实际查询相关: 由于城市不属于县或直辖市,因此没有城市 ID 或县 ID。他们有_many :counties, through: :municipalities

我想通过直辖市查询所有拥有_a_county 的城市。按照惯例,城市不应该有 cityity_ids。如果我分配一个,我应该能够像这样查询所有拥有_a_county 的城市的数据库:

我愿意

# find cities
SELECT  `cities`.* FROM `cities`

  # where municipality_ids match any of the returned municipalities. 
  INNER JOIN `municipalities` ON `cities`.`municipality_id` = `municipalities`.`id`

  #inner join may be wrong here. I'm not sure exactly what that does; I just mimicked the other queries' syntax assuming it will check the records in the 'assemblies' table for a quantity_id.

  # where county_ids match any of the returned counties. 
  INNER JOIN `counties` ON `municipalities`.`county_id` = `counties`.`id`

  # where state_ids match any of the returned states
  INNER JOIN `states` ON `developments`.`state_id` = `states`.`id`

    # where state.country_id = params[:id] 
    WHERE `states`.`country_id` = 1

上面的查询需要城市有一个 Municipality_id 才能工作,但我有点担心这样做会在活动记录中引起一些奇怪的行为。

感谢任何反馈。谢谢!

【问题讨论】:

    标签: ruby-on-rails rails-activerecord relationship has-many-through has-many


    【解决方案1】:

    一个起点可能是嵌套您的has_many :X, through: Y 关联。您可以根据需要创建任意数量的这些,而不会弄乱您的数据库列,它们只会为您提供帮助。例如,以下内容会为您购买:

    @country.states
    @country.counties
    @country.municipalities 
    

    我已经缩短了我的示例,但它可以以相同的方式扩展以包括城市:

    Country 
      has_many :states
      has_many :counties, through: :states
      has_many :municipalities, through: counties
    
    State 
      belongs_to :country
      has_many :counties
    
    County 
      belongs_to :state
      has_many :municipalities
    
    Municipality
      belongs_to :county
    

    【讨论】:

    • 这是一个很干净的想法,但问题是如何获得 x.z,其中 z 有很多 x 到 y,x 有很多 z 到 y。我应该编辑问题标题以更具体地使用连接对象,还是应该打开一个新问题? (我在这里还是个新手,在收到回复后编辑了上一个问题后,我得到了一些反对票)
    猜你喜欢
    • 2017-04-03
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    相关资源
    最近更新 更多