【问题标题】:Rails find all with associationRails 找到所有关联
【发布时间】:2011-02-15 21:20:46
【问题描述】:

我有一个我认为非常简单的问题(著名的遗言)...

我有一个 Category 模型 has_and_belongs_to_many Events。我想构建一个简单而有效的查询来查找具有 1 个或多个事件的所有类别。 (使用 Rails 3)

我确定我在这里有一个愚蠢的时刻 - 任何帮助表示赞赏:)

【问题讨论】:

    标签: ruby-on-rails ruby activerecord associations


    【解决方案1】:

    怎么样:

    Category.find :all,
      :conditions => 'id in (select distinct category_id from categories_events)'
    

    您还可以将此作为命名范围添加到您的 Category 类中,以便您可以说 Category.with_events 例如

    class Category < ActiveRecord::Base
      named_scope :with_events, 
        :conditions => 'id in (select distinct category_id from categories_events)'
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多