0

I have two tables pages and menu_items, pages HAS MANY menu_items and menu_items belongs_to pages. In Rail 4 how can I select only those pages that are not linked with menu_items?

Thanks in advance!

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
Kerozu
  • 673
  • 5
  • 15

2 Answers2

0

Perhaps Page.where is what you're looking for. Effectively the where method calls a search through the Page database for all objects of the specified type. By calling it with the parameter of the menu's id equal to nil, you are searching for all pages where there is no menu id.

Ideally you would like to call Page.where(page.menu_items.empty?), however, of course, this isn't allowed.

Looking around this question is more or less exactly the same as yours. They solve it with:

Page.includes(:menu_items).where( :menu_items => {:page_id=>nil} )
Community
  • 1
  • 1
Vasseurth
  • 6,354
  • 12
  • 53
  • 81
0

Each of the following should work:

Page.includes(:menu_items).where( menu_items: { page_id: nil} )

or

Page.find(:all, conditions: { :menu_items.count: 0 } )

or

Page.where('id NOT IN (SELECT DISTINCT(page_id) FROM menu_items)')
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145