1

(feel free to change the headline to what may be more suitable)

I am using Ruby on Rails and I have two model sets:

  • Page
  • Store

  • A page has_many stores.

  • A store has the attribute status_nbr which ranges from 1-5.

For example, page #1 could have 5 stores where two of them have status_nbr = 1 and three of them have status_nbr = 3.

I want to run a query which to find all Pages where there is no store who has status_nbr = 1. In other words, Pages that lack stores with status_nbr = 1. How do I do that? I assume this can be done with some clever join?

As for now I run a loop:

ok_list = []
Page.all.each do |page|
  ok_list << page.id unless page.stores.where(:status_nbr => 1).blank?
end
@pages = Page.where(:id => ok)

which is very bad/slow programming.

Edit: This is not a duplicate question of the one referred. My model is dependent on another model and the attribute of that other model.

Christoffer
  • 2,271
  • 3
  • 26
  • 57
  • Possible duplicate of [Rails Model find where not equal](https://stackoverflow.com/questions/5426421/rails-model-find-where-not-equal) – Sebastián Palma Sep 26 '19 at 09:46
  • The (important) difference here is that this has to do with another model as well. The question you refer to is if the attribute is in the same model! – Christoffer Sep 26 '19 at 10:19

1 Answers1

-1

This should work.

Page.joins(:store).where.not(store: { status_nbr: 1}).uniq

C dot StrifeVII
  • 1,885
  • 1
  • 16
  • 21
  • This answer does not work, for the same reason as the first one (which is now removed). First of all it would need a .distinct in order to receive unique Pages. Nonetheless, it still shows Pages with stores with status_nbr = 1. I have confirmed by looping the results of this and check for stores with status_nbr == 1. – Christoffer Sep 26 '19 at 14:56
  • I have made and edit, also are these values stored as integers or strings? – C dot StrifeVII Sep 26 '19 at 15:06
  • This should at least be Page.joins(:stores).where.not(stores: { status_nbr: 1}).uniq and although it is elegant it doesn't work. If I do Page.joins(:stores).where.not(stores: { status_nbr: 1}).uniq.each do |page| puts page.stores.where(:status_nbr => 1).count end it still shows Pages where at least some stores have status_nbr = 1. So, thanks, but unfortunately this doesnt work. My suspicion is that there is a need for another type of join but I don't know. – Christoffer Sep 26 '19 at 19:56