Rails Active Record如何检查相关记录不为空

时间:2015-02-18 10:27:51

标签: ruby-on-rails activerecord queryinterface

我无法从Active Record中找到查询界面,只显示至少有一个 产品 <的 类别 / strong>即可。怎么做?

category.rb

class Category < ActiveRecord::Base
  has_many :products
end

product.rb

class Product < ActiveRecord::Base
  belongs_to :category
end

谢谢

2 个答案:

答案 0 :(得分:1)

@categories = Category.joins(:products).where('products.id is not null').group('products.category_id')

它只会显示至少包含一种产品的类别。

答案 1 :(得分:0)

你可以这样做

@categories = Category.joins(:products).where('categories.id is not null').group('products.id')