Using Scopes with Ruby on Rails

0

I need help with a scope, I need to show the products that are not on my list of discounts to add them.

I'm trying with this code:

scope :without_discount, -> (id_params)  {Producto.includes(:detalleld).where.not(:detalleld => { listaid: id_params })}

And he is not showing me all the products but he shows me only those products that are in other discount lists but not those that are not associated to any list.

    
asked by LuisC 13.08.2016 в 05:22
source

1 answer

2

I would do it in the following way if we start from the premise that a product can only be on one list at a time. (If this were not the case, it would be necessary to change to a structure polymorphic )

A Product model with the attributes you need and another List that has many (or one) products

# producto.rb
class Producto 
 belongs_to: lista
end

# lista.rb
class Lista
 has_many: productos
end

In this way, your scope would be much easier

scope :without_discount, -> (id_params) {Producto.includes(:detalleld).where.not(:detalleld => { lista_id: id_params })}

where list_id is an attribute (automatic when the product migration is created) of the Product model that indicates whether the product belongs to a list.

A couple of observations:

  • Beware of plurals in Spanish! Remember that everything that is left to add an 's' at the end you can indicate it in the file pluralizations.rb. More info on link

  • Beware of includes in scopes that querys can get out of hand. I recommend the gem Bullet ( link ) in development that helps detect and eliminate them.

answered by 04.11.2016 в 12:24