Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting records where relation is not empty

I have a one-to-many relationship between Product and ProductCategory.

How do I query all productcategories that have at least one product associated to them?

class Product < ActiveRecord::Base
  belongs_to  :product_category
end

class ProductCategory < ActiveRecord::Base
  has_many :products
end
like image 372
Fellow Stranger Avatar asked Sep 27 '12 15:09

Fellow Stranger


People also ask

How to select rows without NULL values in sql?

Below is the syntax to filter the rows without a null value in a specified column. Syntax: SELECT * FROM <table_name> WHERE <column_name> IS NOT NULL; Example: SELECT * FROM demo_orders WHERE ORDER_DATE IS NOT NULL; --Will output the rows consisting of non null order_date values.

How can you check if a record in a column is not empty?

SELECT * FROM yourTableName WHERE yourSpecificColumnName IS NULL OR yourSpecificColumnName = ' '; The IS NULL constraint can be used whenever the column is empty and the symbol ( ' ') is used when there is empty value.

How to avoid NULL values in select query?

SELECT column_names FROM table_name WHERE column_name IS NOT NULL; Query: SELECT * FROM Student WHERE Name IS NOT NULL AND Department IS NOT NULL AND Roll_No IS NOT NULL; To exclude the null values from all the columns we used AND operator.

How to display only not NULL values in sql?

To display records without NULL in a column, use the operator IS NOT NULL. You only need the name of the column (or an expression) and the operator IS NOT NULL (in our example, the price IS NOT NULL ). Put this condition in the WHERE clause (in our example, WHERE price IS NOT NULL ), which filters rows.


3 Answers

ProductCategory.all(
  :joins => :products, 
  :select => "product_categories.*, count(products.id) as prod_count",
  :group => "product_categories.id"
)

I found out how to solve this thanks to the great Ryan Bates on this screencast: http://railscasts.com/episodes/181-include-vs-joins

like image 124
Fellow Stranger Avatar answered Sep 24 '22 11:09

Fellow Stranger


ProductCategory.includes(:products).where('products.id is not null').all

like image 39
Veraticus Avatar answered Sep 22 '22 11:09

Veraticus


Joins makes an inner join, so the where clause in some of the other answers is superfluous. Grouping by products.id as some others do will repeat the category when the category has multiple products, grouping by the ProductCategory will eliminate dups.

ProductCategory.joins(:products).group('product_categories.id')
like image 21
elc Avatar answered Sep 26 '22 11:09

elc