【问题标题】:Rails 3 SQL query inside nested resources嵌套资源中的 Rails 3 SQL 查询
【发布时间】:2011-10-09 07:01:55
【问题描述】:

假设我在 Rails 应用程序中有一系列嵌套资源(MagazineEditionAd),因此杂志有很多版本,随后会有很多广告。

如何进行查询以在给定杂志的所有版本中制作所有广告,然后按创建日期对它们进行排序?

理想情况下,我希望使用单个 SQL 查询生成一个包含所有结果的数组,而不是对每个版本进行查询然后组合后续数组。

【问题讨论】:

    标签: sql ruby-on-rails nested-resources


    【解决方案1】:

    使用 has_many :through。

    class Magazine < ActiveRecord::Base
      has_many :editions
      has_many :ads, :through => :editions
    end
    
    @magazine.ads.order('created_at')
    

    编辑 Read the docs on has_many :through. It's powerful stuff.

    【讨论】:

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