jeudi 26 septembre 2019

Exclude active record entries based on another active record attribute

(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.

Aucun commentaire:

Enregistrer un commentaire