Tengo objetos que tienen un rango de antigüedad mínimo/máximo:
name: "Event 1" type: Package # inheritance min_age: 1 max_age: 8 category_id: 2 # BirthdayMe gustaría seleccionar y devolver estos objetos en función de la preferencia de edad y tipo del usuario al observar si el rango de edad del objeto satisface el número ingresado.
Actualmente estoy atascado con:
Código del controlador:
age = params[:age] item_type = params[:item_type] @all_items = Item.where("categories.name = ?", 'birthday') @events = @all_items.where("(type: #{item_type}) AND ...here I need to lookup if the #{age} variable is within the object range")Ahora el problema es que necesito elegir un evento de cumpleaños por el número de usuario ingresado, con Rango en el objeto mismo. ¿Hay alguna manera de hacerlo sin pasar por cada objeto?
@events = @all_items.where("type = #{item_type} AND min_age >= #{age} AND max_age <= #{age}")Supongo que las asociaciones se ven de la siguiente manera:
Item has_many :categories Category belongs_to :itemEn este caso
Item.where("categories.name = ?", 'birthday') lo más probable es que falle porque las categories no están unidas con algo como
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "categories"Esto es lo que querrás hacer:
Item.joins(:categories) .where(categories: { name: 'birthday' }) .where("items.type = '#{item_type}' AND items.min_age >= #{age} AND items.max_age <= #{age}") .group('items.id')El uso de BETWEEN de PostgreSQL podría hacer que la consulta se vea mejor y más corta:
Item.joins(:categories) .where(categories: { name: 'birthday' }) .where("items.type = '#{item_type}' AND #{age} BETWEEN items.min_age AND items.max_age") .group('items.id')